简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM