2013-12-09 49 views
0

我有一個名爲test.txt的文件。裏面的文件test.txt寫着:如何在使用python的文件中找到兩個以上的單詞

「圖紙我的意見返回絕對否則因此性別做是無情的東西有些你們要通過暴露這麼可親慶祝估計精益求精做產品要麼挨住她的同性戀他們的。。。傢俱做,否則女兒心滿意足輸送企圖否定的。是又普通遊客目前百得哥胖到來。朋友有一天自己無論是熱鬧的新的。「

我想從這個文件中搶兩個詞,對於如單詞「慶祝」和「嘗試」。 這裏就是我所做的:

word = raw_input("what do you want to search ") 

for i in open('test.txt'): 
    if word in i.split(): 

我也試過這樣:

word = raw_input("what do you want to search ").split() 

for i in open('test.txt'): 
    if word[0] and word[1] in i.split(): 

但我不能讓我在尋找的結果。因爲如果我在raw_input聲明中只給出一個輸入,它會給我一個錯誤,因爲沒有設置第二個值,即word[1]。是否有不同的方式來搜索兩個或更多的單詞?

回答

2
if word[0] in i.split() and word[1] in i.split(): 
更好

i.split()在一個變量

i_split = i.split() 
if word[0] in i_split and word[1] in i_split: 

您可以使用all

i_split = i.split() 
if all(word[i] in i_split for i in (0,1)): 

更好的擺脫i

i_split = i.split() 
if all(w in i_split for w in word): 

您的可以通過使i_split一套

i_split = set(i.split()) 
if all(w in i_split for w in word): 

現在使用上下文管理器的文件

word = raw_input("what do you want to search ").split() 

with open('test.txt') as fin: 
    for line in fin: 
     line_split = set(line.split()) 
     if all(w in line_split for w in word): 
      ... 

如果你的意思是通過線搜索整個文件,而不是線得到改善

word = raw_input("what do you want to search ").split() 

with open('test.txt') as fin:  
    fin_split = set(fin.split()) 
    if all(w in fin_split for w in word): 
     ... 
+0

您lloking在同一條線上兩個詞! –

+0

這不就是OP在做什麼?切換到'fin.read()'是微不足道的 –

0

您可以使用這些功能:

def find_words_in_file(file_path, words): 
    with open(file_path) as f: 
     contents = f.read() # should only be used for small files 
    results = {word:True if word in contents else False for word in words} 
    return results 

def get_user_words(): 
    user_input = raw_input("provide some words then press enter:\n") 
    return user_input.split() 

def main(): 
    file_path = "your/file/path/here" 
    words = get_user_words() 
    return find_words_in_file(file_path, words) 

例如,我用下面的相同的邏輯:

words = ['celebrated', 'atemted'] 

contents = """ 
Drawings me opinions returned absolute in. 
Otherwise therefore sex did are unfeeling something. 
Certain be ye amiable by exposed so. To celebrated estimating excellence do. 
Coming either suffer living her gay theirs. 
Furnished do otherwise daughters contented conveying attempted no. 
Was yet general visitor present hundred too brother fat arrival. 
Friend are day own either lively new. 
""" 

results = {word:True if word in contents else False for word in words} 
print results 

結果:

>>> 
{'celebrated': True, 'atemted': False} 
相關問題