文本文件中的前一个元素计数
Previous element count in text file
我有 2 个包含独特单词的文本文件,每行一个单词分隔。我想找到文件中特定单词之前的行数。假设
bread
pizza
pasta
tomato
是文本文件 1。
pizza
tomato
是文本文件 2。
我想得到
pizza 1
tomato 3
作为输出。我尝试了代码 但由于我的文本文件很大,它无法正常工作(textfile1 包含 45999 行 textfile2 包含 2698 行)。如何解决这个问题?谢谢..
您可以将 textfile2
中的单词读入一个集合,然后使用从 enumerate
生成的索引遍历 textfile1
的行。如果当前索引在上述集合中,则输出具有当前索引的单词:
with open('textfile2') as file:
words = {line.rstrip() for line in file}
with open('textfile1') as file:
for index, line in enumerate(file):
word = line.rstrip()
if word in words:
print(word, index)
我有 2 个包含独特单词的文本文件,每行一个单词分隔。我想找到文件中特定单词之前的行数。假设
bread
pizza
pasta
tomato
是文本文件 1。
pizza
tomato
是文本文件 2。
我想得到
pizza 1
tomato 3
作为输出。我尝试了代码
您可以将 textfile2
中的单词读入一个集合,然后使用从 enumerate
生成的索引遍历 textfile1
的行。如果当前索引在上述集合中,则输出具有当前索引的单词:
with open('textfile2') as file:
words = {line.rstrip() for line in file}
with open('textfile1') as file:
for index, line in enumerate(file):
word = line.rstrip()
if word in words:
print(word, index)