我正在開發一個用戶輸入文本的小程式,我想檢查給定單詞在給定輸入中出現的次數。
# Read user input
print("Input your code: \n")
user_input = sys.stdin.read()
print(user_input)
例如,我在程式中輸入的文本是:
a=1
b=3
if (a == 1):
print("A is a number 1")
elif(b == 3):
print ("B is 3")
else:
print("A isn't 1 and B isn't 3")
要查找的單詞在陣列中指定。
wordsToFind = ["if", "elif", "else", "for", "while"]
基本上我想列印輸入中出現了多少“if”、“elif”和“else”。
如何通過用戶輸入計算給定字串中“if”、“elif”、“else”、“for”、“while”等單詞的出現次數?
uj5u.com熱心網友回復:
我認為最好的選擇是使用tokenizepython的內置模塊:
# Let's say this is tokens.py
import sys
from collections import Counter
from io import BytesIO
from tokenize import tokenize
# Get input from stdin
code_text = sys.stdin.read()
# Tokenize the input as python code
tokens = tokenize(BytesIO(code_text.encode("utf-8")).readline)
# Filter the ones in wordsToFind
wordsToFind = ["if", "elif", "else", "for", "while"]
words = [token.string for token in tokens if token.string in wordsToFind]
# Count the occurrences
counter = Counter(words)
print(counter)
測驗
假設你有一個test.py:
a=1
b=3
if (a == 1):
print("A is a number 1")
elif(b == 3):
print ("B is 3")
else:
print("A isn't 1 and B isn't 3")
然后你運行:
cat test.py | python tokens.py
輸出:
Counter({'if': 1, 'elif': 1, 'else': 1})
優點
只會決議正確的python(語法上)
您只會計算 python 關鍵字(不是代碼文本中出現的每個if,例如,您可以有一行
a = "if inside str"如果不應該被計算在內,我認為
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524742.html
標籤:Python数组用户输入
上一篇:按索引回傳陣列中的多個特定項
