读取文件和搜索词

2024-04-25 22:42:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个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

Tags: to代码youdatadictionarycountlinebe
3条回答

读取文件时,应使用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['a'],如果它存在于dictionary中,否则它将返回字符串'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将为您提供语法高亮显示等功能

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

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

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)是一个更好的选择

相关问题 更多 >