簡體   English   中英

如何檢查句子是否僅包含文件中的單詞

[英]How to check if sentence contains words only from a file

我正在嘗試創建一個程序,該程序檢查用戶輸入的字符串是否僅包含來自文本文件的單詞,該文件將包含英語詞典中的所有單詞。 這將刪除任何語。 如果您還有其他方法可以這樣做,請告訴我,因為我是python的新手。 提前致謝。

  1. 拿字典,將其中的所有單詞放入某種哈希集。
  2. 取句子,將其拆分為單詞,對每個單詞進行哈希處理。 檢查哈希是否在哈希集中發生。

首先,將所有單詞讀入字符串,然后將單詞分成按空格分隔的列表:

words = []

with open('data.txt', 'r') as myfile:
     data = myfile.read().replace('\n', '')

words = data.split()

然后檢查您的單詞是否在列表中:

if checkWord.lower() in words:
    wordCheck = True
def slang_remover(PATH_TO_DICTIONARY_TEXT_FILE):

    #Opening the Dictionary textfile which contain all dictionary words except slangs.
    mydictionaryfile=open(PATH_TO_DICTIONARY_TEXT_FILE)

    #Reading the whole dictionary as a text.
    alltext_from_dictionary=mydictionaryfile.read()

    #Getting the sentence from the User.
    user_sentence=raw_input("Give me the sentence!")

    #Spliting User sentence into word so that check for slang and remove it.
    splited_user_sentence=user_sentence.split()
    slang_removed_splited_user_sentence=[word for word in splited_user_sentence if word in alltext_from_dictionary ]
    slang_removed_user_sentence=' '.join(slang_removed_splited_user_sentence)

    print "Here is the slang removed sentence"
    return slang_removed_user_sentence

像這樣稱呼它: slang_remover("dictionary.txt")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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