繁体   English   中英

读取文件和搜索词

[英]Reading file and search word

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

这就是我的愿望 output:

Please enter an abbreviations: u gtg

output: u got to go

读取文件时,应使用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 function 通常在末尾打印一个换行符,但我们希望将文本保留在一行,所以我告诉它在末尾打印一个空格。 为了让事情看起来更漂亮,我在打印完所有单词后打印一个换行符(否则你的提示将在最后一个字符之后结束)。

Output:

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 package(但还有其他)。

然后您可以通过以下方式创建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() function 从words中创建另一个序列,其中words中的每个缩写将被字典中的值替换。 map() function 将遍历单词中的每个words并调用lambda word: dictionary[key] if word in dictionary else word for each word。 结果将是一个删除了所有缩写的新序列。 新序列中的每个单词都将使用' '.join()由空格连接。

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

要添加到前面的答案,因为您的输入实际上是几个单词, 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'

这个小例子似乎有效

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:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM