python - 在文件中获取一个单词并添加该单词出现的行号并将该数字添加到列表中并添加到字典
问题描述
我正在尝试编写一个函数索引,它采用一个参数,一个文件名(有一个完整的故事),并返回一个字典,其中键是文件中的单词,值是包含唯一且按升序排列的行号的列表) 这些词出现在其中。
为了获得唯一的密钥,我这样做了:
with open(filename) as file:
text = file.read();
list1 = set(text.split())
print(list1)
for line_num, line in enumerate(file):
if any([word in line for word in list1]):
print (line_num, line)
得不到结果。。
编辑:添加示例数据:
LIET
Now, by Saint Peter's Church and Peter too,
He shall not make me there a joyful bride.
I wonder at this haste; that I must wed
Ere he, that should be husband, comes to woo.
I pray you, tell my lord and father, madam,
I will not marry yet; and, when I do, I swear,
It sh
答案应该是——
{'LIET': [1], 'Now,': [3], 'by': [3], 'Saint': [3], "Peter's": [3], 'Church': [3], 'and': [3, 7], 'Peter': [3], 'too,': [3], 'He': [4], 'shall': [4], 'not': [4, 8], 'make': [4], 'me': [4], 'there': [4], 'a': [4], 'joyful': [4], 'bride.': [4], 'I': [5, 7, 8], 'wonder': [5], 'at': [5], 'this': [5], 'haste;': [5], 'that': [5, 6], 'must': [5], 'wed': [5], 'Ere': [6], 'he,': [6], 'should': [6], 'be': [6], 'husband,': [6], 'comes': [6], 'to': [6], 'woo.': [6], 'pray': [7], 'you,': [7], 'tell': [7], 'my': [7], 'lord': [7], 'father,': [7], 'madam,': [7], 'will': [8], 'marry': [8], 'yet;': [8], 'and,': [8], 'when': [8], 'do,': [8], 'swear,': [8], 'It': [9], 'sh': [9]})
解决方案
以下应该可以解决问题
def index(filename):
word_lines = {}
with open(filename) as file:
for line_num, line in enumerate(file.readlines(), 1):
for word in line.split():
if word in word_lines.keys():
if line_num not in word_lines[word]:
word_lines[word].append(line_num)
else:
word_lines[word] = [ line_num ]
return word_lines
print(index('test.txt'))
样本的输出将是:
{'Now,': [1], 'by': [1], 'Saint': [1], "Peter's": [1], 'Church': [1], 'and': [1, 5], 'Peter': [1], 'too,': [1], 'He': [2], 'shall': [2], 'not': [2, 6], 'make': [2], 'me': [2], 'there': [2], 'a': [2], 'joyful': [2], 'bride.': [2], 'I': [3, 5, 6], 'wonder': [3], 'at': [3], 'this': [3], 'haste;': [3], 'that': [3, 4], 'must': [3], 'wed': [3], 'Ere': [4], 'he,': [4], 'should': [4], 'be': [4], 'husband,': [4], 'comes': [4], 'to': [4], 'woo.': [4], 'pray': [5], 'you,': [5], 'tell': [5], 'my': [5], 'lord': [5], 'father,': [5], 'madam,': [5], 'will': [6], 'marry': [6], 'yet;': [6], 'and,': [6], 'when': [6], 'do,': [6], 'swear,': [6], 'It': [7], 'sh': [7]}
推荐阅读
- apache-kafka - 在独立与分布式模式下运行单个 kafka s3 sink 连接器
- python - 计算数据框中特定列(SUM、AVG、STDEV)的所有嵌套级别聚合
- prometheus - Prometheus:使用 https 方案的主机名无效
- python - 跨 Socket 发送数据可能太慢?
- spring - Spring Boot JpaRepository 保存方法抛出 SQLGrammarException:无法提取 ResultSet。但是 findById 方法有效
- javascript - 如何针对正则表达式验证 Html TextAreaFor 中的单行
- java - 多播不同的值
- javascript - 循环访问具有不同 ID 的对象的 JavaScript 数组
- java - 从 ListenerAdapter 创建线程会阻止它监听事件 Java JDA
- python - AttributeError: 'kivy.properties.ObjectProperty' 对象没有属性