简体   繁体   English

如何读取文本文件中有多少数字? Python

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

I don't know nothing about scripting and this code was givin me from a forum that has nothing to do with this type of questions so i ask here to have a better feedback.我对脚本一无所知,这段代码是从一个与此类问题无关的论坛给我的,所以我在这里要求提供更好的反馈。

The "numbers.txt" contains a lot of numbers “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...

When i run the script and choose to see how much is there the number "1" it counts all the "1" include (10,11,12,13 etc...) and it's wrong is not what i need.当我运行脚本并选择查看数字“1”有多少时,它会计算所有“1”包括(10、11、12、13 等),这不是我需要的错误。 How to correct this?如何纠正这个? Anyone could edit this code please, thanks.任何人都可以编辑此代码,谢谢。

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

Assuming your numbers are all separated by whitespace (eg spaces, newlines, tabs) this will give you a count of each occurrence of whatever string you enter:假设您的数字都由空格分隔(例如空格、换行符、制表符),这将为您计算您输入的任何字符串的每次出现次数:

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