Home > Mobile >  Python - IF statement inside a for loop checking on a Json File
Python - IF statement inside a for loop checking on a Json File

Time:12-27

Here is my code, I'm trying to scan user's input against Json file that contains a wordlist of negative words in order to get the sum of negative words in a user's input.

Note: I take the user input in a list.

current Output: No output that relates to the code below is printed.

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")

CodePudding user response:

I think the line

if wordsInTweet in wordList['negative']:

is not what you want. I think you want to check every word separately inside the for loop. So write

if words in wordList['negative']:

In the future, please specify what does the current code do and what do you want it to do.

CodePudding user response:

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")

changed it a bit... words in if condition because that's what you're iterating over and indentation in else

CodePudding user response:

In your comment, you mention that you don't see output from either print statement. This makes me think that your input to the function "wordsInTweet" may be empty. I would suggest checking that that your list of words in the tweet is non-empty.

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

If you are new to Python, I suggest looking into using a debugger in the future. Many IDEs will have a debugger built in, but you can also use a tool such as PDB. Debuggers allow you to step through your code and inspect the contents of your variables.

Also, I would suggest closing your file after you finish reading from it. For more information, see the docs: Reading and Writing File

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