簡體   English   中英

如何讀取文本文件中有多少數字? Python

[英]How to read how much numbers in text file? Python

我對腳本一無所知,這段代碼是從一個與此類問題無關的論壇給我的,所以我在這里要求提供更好的反饋。

“numbers.txt”包含很多數字

10 20 30 40 50
1 2 3 4 5
11 12 13 14 15
3,4,5,6,7,8,9,10
etc...

當我運行腳本並選擇查看數字“1”有多少時,它會計算所有“1”包括(10、11、12、13 等),這不是我需要的錯誤。 如何糾正這個? 任何人都可以編輯此代碼,謝謝。

def main():
    file  = open("numbers.txt", "r").read()
    value  = input("Enter the value: ")
    count = file.count(value)
 
    if count == 0:
        print("Invalid number.")
    else:
        print("Value occurrences: " + str(count))
main()

假設您的數字都由空格分隔(例如空格、換行符、制表符),這將為您計算您輸入的任何字符串的每次出現次數:

value  = input("Enter the value: ")

with open("numbers.txt", "r") as file_handler:

    text = file_handler.read()

    values = text.split()

    selects = [item for item in list if item == value ]

print("Value occurrences: ", str(en(selects)))

暫無
暫無

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

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