简体   繁体   English

我的程序出错-如何在列表上用空格分割单词? Python(二手字典,列表,.txt文件)

[英]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) 我在代码中使用了列表和字典,这些列表和字典似乎可以正常工作,我已经测试了几件事,但是当我输入.txt文件时,一切都很好,并且程序可以正常运行,但是当您输入自己的单词时,程序似乎将所有内容带空格的单词(我的意思的示例:如果我输入家用电话键盘,程序会将所有3个单词都加为一个)

My question is how can I split the words by spaces when the user inputs the words themselves instead of using a .txt file? 我的问题是,当用户自己输入单词而不使用.txt文件时,如何用空格分隔单词?

#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. 我已经测试了您的代码,并且只要在选择了选项a之后,您一次输入一个单词,然后按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: 如果要添加多个单词,并在按Enter之前在单词之间添加空格,请按如下所示修改'if typeFile ==“ a”:'部分:

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. 只要您为字典提供了至少5个不同的单词,您的程序就可以工作了。 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将打印列表中前5个使用过的单词”之后的部分,如下所示:

#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. 我正在使用python 3.6.3,以下代码对我来说很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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