【问题标题】:Python - IF statement inside a for loop checking on a Json FilePython - for 循环中的 IF 语句检查 Json 文件
【发布时间】:2021-12-26 18:41:20
【问题描述】:

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

【问题讨论】:

  • 您能否描述一下您所看到的代码有什么问题,或者是什么不工作。或者你的问题是什么?
  • 当然,对不起!我没有得到与单词总和相关的输出,也没有收到错误消息“未找到否定词”。

标签: python json


【解决方案1】:
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 中的缩进

【讨论】:

  • 感谢您的回复,我按照您的建议进行了更改,但仍然没有收到与此功能相关的输出。注意:只是为了澄清我没有忘记调用该函数。
  • 你能检查 wordsInTweet 是否为空吗?
  • 通过在 for 循环的开头打印一些东西来检查以确保程序正在进入 for 循环
  • 我像你问的那样检查了,似乎循环内的打印命令不起作用但 wordsInTweet 不是空的,它包含用户输入
  • 这不可能...程序必须输入 if 或 else...您能否再次检查您的代码并确保调用 SumOfNegWords 以及代码是否进入 for 循环与否
【解决方案2】:

我觉得行

if wordsInTweet in wordList['negative']:

不是你想要的。我认为您想在 for 循环中分别检查每个单词。所以写

if words in wordList['negative']:

未来,请说明当前代码做什么以及你希望它做什么。

【讨论】:

    【解决方案3】:

    在您的评论中,您提到您没有看到任何一个打印语句的输出。这让我觉得你对函数“wordsInTweet”的输入可能是空的。我建议检查推文中的单词列表是否为非空。

    # Checks that the list is empty or None
    if not wordsInTweet:
        print("Word list was empty")
    

    如果您是 Python 新手,我建议您将来考虑使用调试器。许多 IDE 会内置调试器,但您也可以使用诸如 PDB 之类的工具。调试器允许您单步执行代码并检查变量的内容。

    另外,我建议您在阅读完文件后关闭您的文件。有关更多信息,请参阅文档:Reading and Writing File

    with open('wordList.json') as f:
        wordList = json.load(f)
    # Use wordList below
    

    【讨论】:

    • 我检查了,用户输入不为空,谢谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2019-06-09
    相关资源
    最近更新 更多