2016-11-25 64 views
-1

我試圖讓我的程序通過輸入句子(例如「你好!」) 並查看輸入中的任何單詞是否在列表中。 這裏是迄今爲止代碼:Python如何檢查單詞是否在列表和輸入中?

def findWholeWord(w): 
    return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search 
i.upper() #i is the inputted variable as a string 
WordsDocument = open('WordsDocument.txt').readlines() 
for words in WordsDocument: 
    WordsList.append(words) 
for word in i: 
    if findWholeWord(word) in WordsList: 
     print("Word Match") 

有人可以幫助我建立一個更好的解決方案/解決這一問題,以便它的工作原理?

回答

0
import re 

def findWholeWord(w):    # input string w 

    match_list = []     # list containing matched words 
    input_list = w.split(" ") 

    file = open('WordsDocument.txt', 'r') 
    text = file.read().lower() 
    file.close() 
    text = re.sub('[^a-z\ \']+', " ", text) 
    words_list = list(text.split()) 

    for word in input_list: 
     if word in words_list: 
      print("Word Found: " + str(word)) 
      match_list.append(word) 
    return match_list 
相關問題