拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Python-检查Json档案的for回圈中的IF陈述句

Python-检查Json档案的for回圈中的IF陈述句

白鹭 - 2022-02-11 2010 0 0

这是我的代码,我正在尝试针对包含否定词词表的 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
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *