python - 输出字典中的单词位置
问题描述
我有一个文本文件要分析,要求是输出字典,key是单词,value是单词位置(有些单词在文本中出现了好几次,所以单词有多个位置作为值词典 )。比如任何地方:[1,4,6,8,10]
。但是我的输出只出现在单词的一个位置,比如anywhere [1]
:. 我在这里真的很困惑,这是我的代码和输出。另外,我只能使用内置函数,我不能导入任何其他函数。
file_name = input('Enter the file name: ')
words_data = open(file_name, 'r')
words_list = []
new_word_list = []
word_index= []
dictionary = {}
for line in words_data:
words = line.split()
for word in words:
words_list.append(word.lower())
for word_p in words_list:
word_np = word_p.strip('?.,;:!-')
new_word_list.append(word_np)
if word_np in new_word_list:
word_index.append(new_word_list.index(word_np))
dictionary = {}
for final_word in new_word_list:
word_position = dictionary.get(final_word,None)
if word_position == None:
dictionary[final_word] = new_word_list.index(final_word)
print(dictionary)
#Outputs#
Enter the file name: greenEggsham.txt
{'rain': 420, 'car': 194, 'thank': 778, 'try': 635, 'eggs': 20, 'could': 190, 'or': 42, 'them': 27, 'there': 43, 'fox': 143, 'the': 393, 'see': 216, 'good': 719, 'be': 239, 'train': 301, 'boat': 518, 'would': 37, 'that': 6, 'let': 237, 'so': 632, 'do': 11, 'i': 0, 'with': 83, 'will': 215, 'like': 13, 'ham': 22, 'you': 17, 'green': 19, 'am': 1, 'are': 201, 'goat': 503, 'they': 200, 'here': 41, 'me': 238, 'and': 21, 'eat': 132, 'in': 76, 'house': 78, 'if': 650, 'on': 312, 'say': 391, 'sam-i-am': 7, 'dark': 394, 'not': 12, 'anywhere': 57, 'box': 136, 'sam': 2, 'may': 211, 'a': 77, 'spam': 384, 'tree': 223, 'mouse': 85}
解决方案
每次访问密钥时,您都会覆盖字典值。正如 shaik 提到的,使用列表作为字典值并每次都附加到列表中。
例如:
for final_word in new_word_list:
word_position = dictionary.get(final_word,None)
if word_position == None:
if final_word in dictionary:
dictionary[final_word].append(new_word_list.index(final_word))
else:
dictionary[final_word] = [new_word_list.index(final_word)]
推荐阅读
- typescript - 是否有一种类型级别的方法可以从类中提取具有默认值的属性?
- asp.net-core - 添加 ResponseCache 属性时记录缓存控制警告
- php - 如何绕过网站重定向屏幕?
- express - 在快速应用程序中使用压缩中间件不起作用
- r - 在 ggplot 中绘制具有聚集标准误差的回归的置信区间
- xcode - 转换为 swift 4:找不到构建输入文件 target:Tests/_5__2Tests.swift'
- c# - 是否有与 Java 的 :: 表示法等价的指代成员函数?
- interface - 仅在 localhost 接口上使 socat 开放端口
- nvidia - 同时为 GPGPU 运行 NVIDIA,为图形运行 Intel
- angular - 离子:Firebase 查询返回丢失的数据