【问题标题】:Find if lines on one file appear as words in the lines of another file in Python查找一个文件上的行是否在 Python 中显示为另一个文件的行中的单词
【发布时间】:2021-05-25 13:29:29
【问题描述】:

我有两个文本文件。文件一每行一个单词,大约有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 进行比较以获得匹配数。有没有更好的方法同时完成这两个步骤?

【问题讨论】:

  • 尝试使用字典..
  • 你试过了吗?
  • 让文件 1 成为字典?
  • 要使其成为计数器,您可以使用 Dictionary..
  • 请将您的输入文件包含为格式化文本,而不是屏幕截图。这样,我们可以将它们复制到我们的计算机上,并向您展示我们的代码给出的输出,而无需自己输入文件。您可以通过在文件内容前后的行上添加三个反引号 ( ` ) 将文本格式化为代码块。 Formatting help

标签: python


【解决方案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")

如果您想计数file1 中每个单词在file2 中的出现次数,您需要编写更多代码。

首先,读取第二个文件并计算每个单词的出现次数。您可以为此使用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() 函数:

total_common_count = sum(file2_wordcount.get(word, 0) for word in file1_words)

【讨论】:

    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多