2017-08-18 32 views
0

我是全新的python,但我正在開發一個小型項目。 我有一個文件和B檔象下面這樣: enter image description here如何使用Python在兩個csv文件中查找相同的單詞3

而且我要來比較& B和得到,在既有&乙文件的話。 我嘗試了幾種方法,但無法解決問題。

任何人都可以幫助我嗎?謝謝!

+2

目前尚不清楚您的期望輸出是什麼。 –

+0

在我的例子中,我想獲得'主要','統計',因爲他們都在A和B. – Laura

回答

1

Rthomas529有正確的想法,但它陷入了一些陷阱。它忽略了標點符號不一致,大小寫不一致或者帶有多個詞的行。

# Load the files for processing 
file_1 = open('f1.txt') 
file_2 = open('f2.txt') 

# Prep some empty sets to throw words into 
words_1 = set() 
words_2 = set() 

for word in file_1.read().split(): 
    cleaned_word = ''.join([ 
     i for i in list(word.lower()) 
     if i.isalpha() or i == "'" 
    ]) 
    if cleaned_word != '': # Just in case! 
     words_1.add(cleaned_word) 

for word in file_2.read().split(): 
    cleaned_word = ''.join([ 
     i for i in list(word.lower()) 
     if i.isalpha() or i == "'" 
    ]) 
    if cleaned_word != '': # Just in case! 
     words_2.add(cleaned_word) 

similar_words = words_1 & words_2 
+0

嗨喬丹,它的工作!!!!!非常感謝你!!!!!!!你讓我今天一整天都感覺很好! – Laura

0

您可以創建2個列表並進行比較。

list1 = [] 
list2 = [] 

with open('file1', 'r+') as myfile1: 
    for line in myfile1: 
     list1.append(line) 

with open('file2', 'r+') as myfile2: 
    for line in myfile2: 
     list2.append(line) 

compare = set(list1) & set(list2) 
+0

謝謝!我嘗試使用set,但它說:TyperError:不支持的操作數類型爲&:'set'和'list'。我想我不能直接設置,因爲我實際上是將列表([[],[],[],[]])與列表進行比較?我不知道熊貓是否可以做到這一點?或者我需要通過使用你的方法for循環? – Laura

+0

看看喬丹辛格的答案。我沒有給你足夠深的答案。 – Rthomas529

+0

如果你已經將你的列表格式化得很好,那麼mapped1 = [我爲我在列表2中,如果我在列表1中]我將在列表中工作。用list1 = [['a','x'],['b','x'],['c','x']] list2 = [['a','x'],[ 'a','z'],['b','x']]作爲測試。 – Rthomas529

相關問題