简体   繁体   中英

Error on my program - How to split words by spaces on a list? Python (used Dictionaries, Lists, .txt file)

Hey my program has this which I think should work, I have gone through the whole program and everything seems fine. But somehow the program doesn't split the words in the list by spaces. I have used lists and dictionaries in my code which seem to work, I have tested a few things but when I input the .txt file everything is fine and the program works perfectly but when you input your own words the program seems to put all of the words with spaces (example of what I mean: if I input house phone keyboard the program adds all 3 words as if they were one)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file?

#These are the helper variables
wordsList = []
wordsDict = {}
words = 0
typeFile = 0
textFile = 0
text = 0
sortValue = 0 
#Here we ask the person if they want to input their own words or use a .txt     
file
print("Input 'a' to input your own words or input 'b' to input text from a 
.txt file")
typeFile = input()

#Here we make an if statement if they chose to input their own words
if typeFile == "a":
    print("enter 'x' when finished")
    while True:
        #Here we ask the user to input their words
        print("Input your words")
        words = input()
        #This will finish asking for input when the user enters x
        if words == 'x':
            break
        #this puts the words on the list
        wordsList.append(words)
#Here we make an if statement if they chose to use a .txt file
if typeFile == "b":
    #This asks for the .txt file they want to open
    words = input("input which .txt file you would like to use   
    (text_file.txt)")
    #This opens the file
    textFile = open(words, 'r')
    text = textFile.read()
    #This adds the words of the file into the list and separates each word     
    by spaces
    wordsList = text.split()

#This sorts the list
for text in range(len(wordsList)):
        #This looks if the word has been added to the dictionary
        if wordsList[text] in wordsDict.keys():
            #this will add a +1 value to the word if it is in already in the     
dictionary
            wordsDict[wordsList[text]] += 1
        #This looks if the word has been added to the dictionary
        if wordsList[text] not in wordsDict.keys():
            #this adds the word to the dictionary if it isnt already in
            wordsDict[wordsList[text]] = 1

#This sorts the words from lowest to highest
sortValue = sorted(wordsDict.items(), key = lambda t:t[1])
#These will print the top 5 used words in the list
print("These are the most used 5 words")
for num in range(1,6):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")

I have tested your code, and it works fine as long as: after choosing option a, you enter one word at a time, and then press enter. If you want to add multiple words together, with spaces in between them before pressing enter, then modify the 'if typeFile == "a":' section as follows:

if typeFile == "a":
print("enter 'x' when finished")
while True:
    #Here we ask the user to input their words
    print("Input your words")
    words = input()
    #This will finish asking for input when the user enters x
    if words == 'x':
        break
    #this puts the words on the list
    if ' ' in words:
        words=words.split()
        wordsList.extend(words)
    else:
        wordsList.append(words)

Your program should then work, provided you provide at least 5 different words for the dictionary. If you do not, you will get a 'list index out of range' statement. To solve this, modify the section after "#These will print the top 5 used words in the list" as follows:

#These will print the top 5 used words in the list
print("These are the most used 5 words")
if len(wordsDict)<5:
    highest=len(wordsDict)
else:
    highest=6
for num in range(1,highest):
    print(num,':',sortValue[num*-1])
words = input("Press return to exit.")

I'm using python 3.6.3 and the following code works fine for me.

import os

cmd = None
words_list = list()
words_dict = dict()

while cmd != 'x':
    cmd = input('What you want to do? [a] to enter your own sentence; [i]mport a file; e[x]it:  ')
    if cmd == 'a':
        os.system('clear')
        sentence = input('Enter your sentence: ')
        split_sentence = sentence.split(' ')
        words_list.append(split_sentence)
    elif cmd == 'i':
        # Add code to read each line in file.
        os.system('clear')
        print('Importing file...')
    elif cmd != 'x':
        os.system('clear')
        print(f'{cmd} is an invalid command.')
    else:
        os.system('clear')
        print('Good Bye!')


def list_to_dict(sentence_list):
    for i in sentence_list:
        for j in i:
            if j in words_dict:
                words_dict[j] += 1
            else:
                words_dict[j] = 1
    return words_dict


print(list_to_dict(words_list))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM