[英]Find if lines on one file appear as words in the lines of another file in Python
我有两个文本文件。 文件一每行一个单词,大约有10Klines。 我的第二个文件是语料库文件,它有大约 69k 行,里面有句子。 每一行都是一个单独的句子
文件 1 看起来像这样
文件 2 看起来像这样
在文件 1 中,每一行都被视为一个单词。 我需要查找文件 1 中的单词是否作为单词出现在文件 2 的句子中,以及它们是否确实有多少出现在语料库文件中。 我尝试了以下代码,但它返回空列表。 关于为什么返回空列表的任何线索?
f=open('Corpus_WX.txt',encoding='utf-8')
for count in range(0,68630):
g=f.readline()
words=g.split()
x=open("Processed_data_edit.txt")
h=x.readline()
word=h.split()
x.close()
z=list(set(words).intersection(word))
with open("New_Matches.txt", 'a', encoding='utf-8') as file:
file.write(str(z))
file.write("\n")
file.close()
count=count+1
我的逻辑是在这里找到共同的元素,然后再次与文件 1 进行比较以获得匹配数。 有没有更好的方法可以同时完成这两个步骤?
如果您只需要找出file2
中有多少单词出现在file1
中,您只需读取两个文件并找到包含两个文件中单词的集合的交集的大小。
with open("file1.txt") as f:
file1_words = f.readlines()
with open("file2.txt") as f:
file2_words = f.read().split() # Read everything and split by whitespace
file1_words = set(file1_words)
file2_words = set(file2_words)
common_words = file1_words.intersection(file2_words)
print(f"File1 and File2 have {len(common_words)} words in common")
如果要计算file2
中file1
中每个单词的出现次数,则需要编写更多代码。
首先,读取第二个文件并计算每个单词的出现次数。 您可以为此使用collections.Counter
,但如果您正在学习,编写自己的代码非常容易:
with open("file2.txt") as f:
file2_words = f.read().split() # Read everything, then split by whitespace
file2_wordcount = dict() # Empty dictionary
for word in file2_words:
old_count = file2_wordcount.get(word, 0) # Get the count from the dict. Or 0 if it doesn't exist
file2_wordcount[word] = old_count + 1 # Set the new count
在这个块的末尾,我们有一个字典file2_wordcount
,它将每个单词映射到第二个文件中的计数。 接下来,我们需要从第一个文件中读取单词并找出它们在另一个文件中出现的次数。
# Now, read the lines from file 1
with open("file1.txt") as f:
file1_words = f.readlines() # Since you have one word per line.
# Convert it into a set to remove duplicates
file1_words = set(file1_words)
for word in file1_words:
count = file2_wordcount.get(word, 0) # Get the count from the dict. Or 0 if it doesn't exist
print(word, count) # Print them both
或者,要获得总数,请使用sum()
function:
total_common_count = sum(file2_wordcount.get(word, 0) for word in file1_words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.