如何打开和读取文本文件并计算介词的频率(已经在元组中指定)并创建一个字典,其中包含介词的键和频率值。
答案 0 :(得分:1)
我希望我能正确理解你的问题。
这是打开和阅读文本文件的简单方法:
file = open("filename", 'r') #'r' means read mode
content = file.read() #content is a string of the entire text file
content = content.lower() #assuming your tuple of prepositions are lower case
words = content.split() #splits content into list of word separated by space
file.close() #closes the file after you already have the contents
现在只需追溯你的介词元组:
#Let's call your tuple preps
freq = []*len(preps)
for i in range(len(preps)):
freq[i] = words.count(preps[i])
现在写下你的密钥:
key = file.open("filename", 'w') #'w' means write mode
key.write("\n".join([prep[i] + " " + str(freq[i]) for i in range(len(prep))]))
key.close()