[英]Reading a text file and replacing it to value in dictionary
我有一本 python 制作的字典。我還有一個文本文件,其中每一行都是一個不同的詞。 我想根據字典的鍵檢查文本文件的每一行,如果文本文件中的行與鍵匹配,我想將該鍵的值寫入 output 文件。 是否有捷徑可尋。 這可能嗎?
例如,我正在這樣閱讀我的文件:
test = open("~/Documents/testfile.txt").read()
對其進行標記化,對於我想查找字典的每個單詞標記,我的字典設置如下:
dic = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
如果我在文件中遇到字母'a'
,我希望它為 output ["ah0", "ey1"]
。
你可以試試:
for line in all_lines:
for val in dic:
if line.count(val) > 0:
print(dic[val])
這將查看文件中的所有行,如果該行包含來自 dic 的字母,那么它將在字典中打印與該字母關聯的項目(您必須執行類似all_lines = test.readlines()
的操作來獲取所有列表中的行) dic[val]
給出分配給值["ah0", "ey1"]
的列表,因此您不僅需要打印它,還可以在其他地方使用它
你可以試試這個:
#dictionary to match keys againts words in text filee
dict = {"a": ["ah0", "ey1"], "a's": ["ey1 z"], "a.": ["ey1"], "a.'s": ["ey1 z"]}
# Read from text filee
open_file = open('sampletext.txt', 'r')
lines = open_file.readlines()
open_file.close()
#search the word extracted from textfile, if found in dictionary then print list into the file
for word in lines:
if word in dict:
write_to_file = open('outputfile.txt', 'w')
write_to_file.writelines(str(dict[word]))
write_to_file.close()
注意:如果您讀取的文本文件有多行,您可能需要去除換行符“\n”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.