我正在从教科书上做练习,我坚持了三天,最后我决定在这里寻求帮助。
问题是:
编写一个读取文本文件内容的程序。该程序应创建一个字典,其中的键值对描述如下:
•键。键是在文件中找到的单个单词。
•价值观。每个值都是一个列表,其中包含在文件中找到单词(键)的行号。
例如:假设在第7、18、94和138行中找到“机器人”一词。字典中将包含一个元素,其中键为字符串“机器人”,而值是包含数字7的列表。 18、94和138。
构建字典后,程序应创建另一个文本文件,称为单词索引,列出字典的内容。单词索引文件应包含按字母顺序存储在字典中的单词的单词列表,以及单词在原始文件中出现的行号。
图9-1显示了原始文本文件(Kennedy.txt)及其索引文件(index.txt)的示例。
这是我到目前为止尝试过的代码,功能尚未完成,不确定下一步该怎么做:
def create_Kennedytxt():
f = open('Kennedy.txt','w')
f.write('We observe today not a victory\n')
f.write('of party but a celebration\n')
f.write('of freedom symbolizing an end\n')
f.write('as well as a beginning\n')
f.write('signifying renewal as well\n')
f.write('as change\n')
f.close()
create_Kennedytxt()
def split_words():
f = open('Kennedy.txt','r')
count = 0
for x in f:
y = x.strip()
z = y.split(' ') #get individual character to find its index
count+=1 #get index for each line during for loop
split_words()
谁能帮助我解答代码或给我一些提示?答案不应该是导入任何东西,而只能使用方法和函数来实现。我将不胜感激!
这是一个三步过程:
The dictionary will be a keys with lists.
To do this, you can create a program like this:
keys_in_file = {}
with open ('Kennedy.txt', 'r') as f:
for i,line in enumerate(f):
words = line.strip().split()
for word in set(words):
keys_in_file.setdefault(word, []).append(i+1)
print (keys_in_file)
The output of the file you provided (Kennedy.txt) is:
{'today': [1], 'victory': [1], 'observe': [1], 'a': [1, 2, 4], 'We': [1], 'not': [1], 'celebration': [2], 'of': [2, 3], 'party': [2], 'but': [2], 'freedom': [3], 'an': [3], 'symbolizing': [3], 'end': [3], 'as': [4, 5, 6], 'well': [4, 5], 'beginning': [4], 'renewal': [5], 'signifying': [5], 'change': [6]}
If you want to ensure that all words (We
, WE
, we
) get counted as same word, you need to convert words to lowercase.
words = line.lower().strip().split()
If you want the values to be printed in the format of index.txt
, then you add the following to the code:
for k in sorted(keys_in_file):
print (k+':', *keys_in_file[k])
输出将如下所示:注意:我转换We
为小写字母,以便稍后以字母顺序显示
a: 1 2 4
an: 3
as: 4 5 6
beginning: 4
but: 2
celebration: 2
change: 6
end: 3
freedom: 3
not: 1
observe: 1
of: 2 3
party: 2
renewal: 5
signifying: 5
symbolizing: 3
today: 1
victory: 1
we: 1
well: 4 5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句