簡體   English   中英

如何根據 Python 中的用戶輸入設置變量的值?

[英]How do you set the value of a variable based on user input in Python?

在我的程序中,用戶可以輸入單詞列表或字母 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 時。 當用戶輸入 n 時,我希望 list2 生成一個詞頻表。

我沒有收到任何錯誤。 在這一點上只是直接進入程序的末尾並返回我在其中的最終打印行,所以我知道它沒有調用 if 語句。

當然,這樣做的方法是替換:

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

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

不?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM