【问题标题】:Reading file and search word读取文件和搜索词
【发布时间】:2021-07-18 17:06:23
【问题描述】:

我写了一个python代码想要读取一个文本文件,用户可以输入单词,它会从文本文件中打印出想要的单词。

文本文件示例如下:

u:you
ttyl:talk to you later
l8:late
brb:be right back
lol:laughing out loud
bbl:be back later
tldr:too long; didn't read
rofl:rolling on floor laughing
gtg:got to go

这是我目前的代码:

dictionary = {}
file = open('abbreviations.txt', 'r')
lines = file.readlines()
count = 1
for line in lines:
    data = line.split(":")
    dictionary[data[0]] = data[1]
    print("Line{}: {}".format(count, line.strip()))
    count += 1

word = input("Please enter an abbreviations: ")
if dictionary.has_key(word):
  print(dictionary[word])
else:
  print(word)

当我运行它时,它在第 12 行显示如下错误:

AttributeError: 'dict' object has no attribute 'has_key'

这是我想要的输出:

Please enter an abbreviations: u gtg

output: u got to go

【问题讨论】:

    标签: python


    【解决方案1】:

    读取文件时,应使用with 语句:

    dictionary = {}
    
    with open('abbreviations.txt') as fp:
        for line in fp:                              # loop over lines in file
            word, explanation = line.split(':', 1)   # only split on the first :
            dictionary[word] = explanation.strip()   # remove final newline
    

    如果您想查看字典,请取消注释以下行:

    # import json
    # print(json.dumps(dictionary, indent=4))
    

    您的描述与您的代码并不完全匹配,所以我按照您的描述,即展开所有字典单词:

    words = input("Please enter an abbreviations: ")
    for word in words.split():                          # split input into individual words
        print(dictionary.get(word, word), end=' ')
    print()  # final newline
    

    dictionary.get('a', 'b') 如果存在于dictionary 中,则返回dictionary['a'],否则返回字符串'b'。上面我用它来返回查找词本身,如果它不在字典中。 print 函数通常在末尾打印一个换行符,但我们希望将文本保留在一行,所以我告诉它在末尾打印一个空格。为了让事情看起来更漂亮,我在打印完所有单词后打印一个换行符(否则您的提示将在最后一个字符之后结束)。

    输出:

    Please enter an abbreviations: u gtg
    you got to go
    

    除此之外:如果您可以使用现有的文件格式,那么创建自己的文件格式来存储数据通常不是一个好主意。

    如果您将abbreviations.txt 更改为(即仅在冒号后添加一个空格):

    u: you
    ttyl: talk to you later
    l8: late
    brb: be right back
    lol: laughing out loud
    bbl: be back later
    tldr: too long; didn't read
    rofl: rolling on floor laughing
    gtg: got to go
    

    使其有效 YAML 并且您可以使用 yaml 库来读取文件。我喜欢ruamel.yaml 包(但还有其他)。

    然后您可以通过以下方式创建dictionary

    from ruamel.yaml import YAML
    yaml = YAML(typ='safe')
    
    dictionary = {}
    
    with open('abbreviations.txt') as fp:   # see note below
        dictionary = yaml.load(fp)
    

    注意:将文件重命名为 abbreviations.yaml 将在大多数编辑器中为您提供语法突出显示等。

    【讨论】:

    • 嗨,我了解它背后的概念和想法,谢谢。如果我希望它能够同时处理大写和小写怎么办?有什么建议吗?
    • 这取决于您处理大写/小写的含义...如果您只想在输入中处理混合大小写,通常的方法是在查找之前只小写word
    • 我猜你的意思是小写用户输入,如果正确的话?
    【解决方案2】:

    if dictionary.has_key(word): 替换为if dictionary.get(word):

    if dictionary.get(word):
      print(dictionary[word])
    else:
      print(word)
    

    【讨论】:

      【解决方案3】:

      has_key() 已弃用,并已在 Python 3 中删除。要检查成员资格,请使用 in 运算符:

      if word in dictionary:
        print(dictionary[word])
      else:
        print(word)
      

      如果输入中有多个用空格分隔的单词,例如u gtg,则需要先将它们拆分。那么这两行就是你所需要的:

      words = input("Please enter the abbreviations: ").split();
      print(" ".join(map(lambda word: dictionary[word] if word in dictionary else word, words)))
      

      在这里,输入中的单词将被空格分割并存储在words中。接下来,我使用map() 函数从words 创建另一个序列,其中words 中的每个缩写将被字典中的值替换。 map() 函数将遍历words 中的每个单词,并为每个单词调用lambda word: dictionary[key] if word in dictionary else word 。结果将是一个删除了所有缩写的新序列。新序列中的每个单词都将使用' '.join() 用空格连接。

      最后,您必须使用file.close() 关闭文件以释放文件。或者正如@thebjorn 提到的,使用上下文管理器 (with) 是一个更好的选择。

      【讨论】:

        【解决方案4】:

        这个小例子似乎有效

        abr_file = 'abbreviations.txt'
        
        with open(abr_file, 'rt') as f:
            lines = f.readlines()
        
        abbr_dict = {}
        for line in lines:
            k, v = [v.strip() for v in line.strip('\n').split(':')]
            abbr_dict[k] = v
        
        while True:
            sentence = input('Please give me a sentence with abbreviations: ')
            words = [w.strip() for w in sentence.split()]
            full_words = []
            for word in words:
                if word in abbr_dict:
                    full_words.append(abbr_dict[word])
                else:
                    full_words.append(word)
        
            full_sentence = ' '.join(full_words)
            print(full_sentence)
        
        Please give me a sentence with abbreviations: u gtg
        you got to go
        Please give me a sentence with abbreviations:
        

        你只需要修正它的标点符号。

        【讨论】:

          【解决方案5】:

          要补充上一个答案,由于您的输入实际上是几个词,ugtg,您需要拆分输入字符串并检查每个标记。比如:

          words = input("Please enter an abbreviations: ")
          out = []
          for word in words.split():
              w = dictionary.get(word, word)  # Get word if in dict, or just return the word if not
              out.append(w)
          ' '.join(out)
          

          然后u gtg 的输入返回:

          'you got to go'
          

          【讨论】:

            猜你喜欢
            • 2013-09-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-07-30
            • 2011-07-03
            • 2014-12-28
            • 1970-01-01
            • 2018-03-02
            相关资源
            最近更新 更多