簡體   English   中英

查找一個文件上的行是否在 Python 中的另一個文件的行中顯示為單詞

[英]Find if lines on one file appear as words in the lines of another file in Python

我有兩個文本文件。 文件一每行一個單詞,大約有10Klines。 我的第二個文件是語料庫文件,它有大約 69k 行,里面有句子。 每一行都是一個單獨的句子

文件 1 看起來像這樣

文件1圖像 .

文件 2 看起來像這樣

文件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")

如果要計算file2file1中每個單詞的出現次數,則需要編寫更多代碼。

首先,讀取第二個文件並計算每個單詞的出現次數。 您可以為此使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM