這是我的代碼,我正在嘗試針對包含否定詞詞表的 Json 檔案掃描用戶的輸入,以便獲得用戶輸入中否定詞的總和。
注意:我在串列中獲取用戶輸入。
當前輸出: 未列印與以下代碼相關的輸出。
def SumOfNegWords(wordsInTweet):
f = open ('wordList.json')
wordList = json.load(f)
NegAmount = 0
for words in wordsInTweet: #for words in the input
if wordsInTweet in wordList['negative']:
NegAmount = 1
print("The Sum of Negative Words =", NegAmount)
else: print("No negative words found")
uj5u.com熱心網友回復:
我認為線
if wordsInTweet in wordList['negative']:
不是你想要的。我認為您想分別檢查 for 回圈中的每個單詞。所以寫
if words in wordList['negative']:
將來,請說明當前代碼做什么以及您希望它做什么。
uj5u.com熱心網友回復:
def SumOfNegWords(wordsInTweet):
f = open ('wordList.json')
wordList = json.load(f)
NegAmount = 0
for words in wordsInTweet: #for words in the input
if words in wordList['negative']:
NegAmount = 1
print("The Sum of Negative Words =", NegAmount)
else:
print("No negative words found")
words在 if 條件中稍作更改,因為那是您要迭代的內容并在 else 中縮進
uj5u.com熱心網友回復:
在您的評論中,您提到您沒有看到任一列印陳述句的輸出。這讓我認為您對函式“wordsInTweet”的輸入可能是空的。我建議檢查您在推文中的單詞串列是否為非空。
# Checks that the list is empty or None
if not wordsInTweet:
print("Word list was empty")
如果您不熟悉 Python,我建議您將來考慮使用除錯器。許多 IDE 將內置除錯器,但您也可以使用諸如PDB 之類的工具。除錯器允許您單步除錯代碼并檢查變數的內容。
另外,我建議您在閱讀完檔案后關閉您的檔案。有關更多資訊,請參閱檔案:讀取和寫入檔案
with open('wordList.json') as f:
wordList = json.load(f)
# Use wordList below
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/394280.html
