我的任务是建立一个程序,要求输入单词。我要编写一个程序来搜索字典中的单词。 (我已经组成了) [我的提示是:您会找到单词的第一个字符。获取以该字符开头的单词列表。 遍历列表以查找单词。] 到目前为止,我有以下代码:
Word = input ("Search word: ")
my_file = open("input.txt",'r')
d = {}
for line in my_file:
key = line[0]
if key not in d:
d[key] = [line.strip("\n")]
else:d[key].append(line.strip("\n"))
我已经接近了,但是我被困住了。预先谢谢你!
user_word=input("Search word: ")
def file_records():
with open("input.txt",'r') as fd:
for line in fd:
yield line.strip()
for record in file_records():
if record == user_word:
print ("Word is found")
break
for record in file_records():
if record != user_word:
print ("Word is not found")
break
答案 0 :(得分:0)
您可以这样做,
words = []
with open("input.txt",'r') as fd:
words = [w.strip() for w in fd.readlines()]
user_word in words #will return True or False. Eg. "americophobia" in ["americophobia",...]
fd.readlines()将文件中的所有行读取到一个列表中,然后w.strip()应该去除所有开头和结尾的空格(包括换行符)。其他尝试-w.strip(\ r \ n \ t)
[w.strip() for w in fd.readlines()]
在python中称为list comprehension
只要文件不是太大,这应该起作用。如果有数百万条记录,则可能要考虑创建一个genertor函数来读取文件。像
def file_records():
with open("input.txt",'r') as fd:
for line in fd:
yield line.strip()
#and then call this function as
for record in file_records():
if record == user_word:
print(user_word + " is found")
break
else:
print(user_word + " is not found")
PS:不确定为什么需要python字典。你的教授会说英语词典的:)