2014-12-03 178 views
0

我想在文本文件中找到匹配存儲在名爲items的現有列表中的單詞的單詞,該列表是在前一個函數中創建的,我希望能夠在下一個函數中使用列表,但我不確定如何做到這一點,我嘗試使用類,但我不能正確的。我無法弄清楚其他代碼的問題。我試着在沒有類和列表的情況下運行它,並且用第8行中的一個單詞替換第8行中的列表'items []',即使沒有錯誤出現,它仍然沒有做任何事情。當下面的代碼運行時,它會輸出:「請包含有效的文本文件名稱:」並停在那裏。如何在Python中搜索特定單詞的文本文件

class searchtext(): 
    textfile = input("Please entre a valid textfile name: ") 
    items = [] 

    def __init__search(self): 
     with open("textfile") as openfile: 
      for line in openfile: 
       for part in line.split(): 
        if ("items[]=") in part: 
         print (part) 
        else: 
         print("not found") 

從包含在先前的功能,看起來像這樣的話另一個文本文件創建的列表和它的作品,因爲它應該,如果是任何幫助:

def createlist(): 
    items = [] 
    with open('words.txt') as input: 
     for line in input: 
      items.extend(line.strip().split(',')) 
    return items 

print(createlist()) 

回答

0

這可能是一個位清潔劑。我覺得上課在這裏是一種矯枉過正的行爲。

def createlist(): 
    items = [] 
    with open('words.txt') as input: 
     for line in input: 
      items.extend(line.strip().split(',')) 
    return items 

print(createlist()) 
# store the list 
word_list = createlist() 

with open('file.txt') as f: 
    # split the file content to words (first to lines, then each line to it's words) 
    for word in (sum([x.split() for x in f.read().split('\n')], [])): 
     # check if each word is in the list 
     if word in word_list: 
      # do something with word 
      print word + " is in the list" 
     else: 
      # word not in list 
      print word + " is NOT in the list" 
-2

有沒有像正則表達式匹配https://docs.python.org/3/howto/regex.html

items=['one','two','three','four','five'] #your items list created previously 
import re 
file=open('text.txt','r') #load your file 
content=file.read() #save the read output so the reading always starts from begining 
for i in items: 
    lis=re.findall(i,content) 
    if len(lis)==0: 
     print('Not found') 
    elif len(lis)==1: 
     print('Found Once') 
    elif len(lis)==2: 
     print('Found Twice') 
    else: 
     print('Found',len(lis),'times') 
+0

這並不能解決任何問題。請提交一個完整的答案,而不僅僅是鏈接和僞代碼剪輯 – 2014-12-03 11:44:31

+0

我試圖給提問者提供一個自己嘗試的建議,現在這裏是一個更好的詳細答案 – 2014-12-04 06:01:27

1

可以正則表達式使用以下方法:

>>> import re 
    >>> words=['car','red','woman','day','boston'] 
    >>> word_exp='|'.join(words) 
    >>> re.findall(word_exp,'the red car driven by the woman',re.M) 
    ['red', 'car', 'woman'] 

第二個命令創建的分隔可以接受的單詞表「 |」。要在文件上運行該文件,只需替換open(your_file,'r').read()「由該女性驅動的紅色汽車」中的字符串即可。

相關問題