如何根据Python中的用户输入设置变量的值?

时间:2019-06-22 21:48:42

标签: python python-3.x user-input

在我的程序中,用户可以输入单词列表或字母n。我想做的是当他们输入n时,它希望它设置将用户输入保存到问号(?)的变量的值。

也在我的程序中,用户输入了一个不同的列表,如果输入n,我希望程序生成一个单词频率表。

我遇到的问题是,当我为用户输入是否为n编写if语句时,我不认为这是在更改值或创建频率表。

我已经转移了程序中代码的位置。无论我在代码中的任何位置,都无法从任何if语句获得响应。本来我以为该程序是我将其放到程序结尾处,并且由于它是从上到下阅读的,所以没有任何反应。现在,我不确定。

我已经包含了可以一起使用的代码,因此我不会粘贴整个程序。

# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
                  "Please separate each entry with a comma.\n If you would like to just search for question marks"
                  "please just type n.")
# Holding list, using comma as a way to separate the given words and symbols
list1 = list(user_keywords.split(','))
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)

# Ask user for needed repeating words
user_repeating = input("What repeating words would you like to search the provided file for?\n"
                  "Please separate each entry with a comma. \n If you would like a frequency table for all words"
                   "two letters or more, please type n.")
# Holding list, using comma as a way to separate the given words and symbols
list2 = list(user_repeating.split(','))
# Print list for user to see
print("You have entered the following words: ", list2)

frequency = {}

# Check to see if list1 has no parameters and sets to ?
if list1 == 'n':
    list1 = '?'
    print("We will search for any question marks.")

# Check to see if list2 has no parameters and creates a frequency array
if list2 == 'n':
    document_text = open (path1, 'r')
    text_string = document_text.read().lower()
    match_pattern = re.findall(r'\b[a-z]{2-20}\b', text_string)
    print("We will look for all word frequencies.")

    for word in match_pattern:
        count = frequency.get(word,0)
        frequency[word] = count + 1

    frequency_list = frequency.keys()

    for words in frequency_list:
       print(words, frequency[words])

我希望将list1设置为?当用户输入n时。我希望list2会在用户输入n时生成一个词频表。

我没有收到任何错误。此时,直接进入程序的结尾并返回我在其中的最终打印行,所以我知道它没有调用if语句。

1 个答案:

答案 0 :(得分:0)

确定要这样做的方法是替换:

list1 = list(user_keywords.split(','))

使用

list1 = '?' if user_input == 'n' else list(user_keywords.split(','))

不?