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()
CodePudding user response:
Assuming your numbers are all separated by whitespace (e.g. 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 values if item == value ]
print("Value occurrences: ", str(len(selects)))