Counting all the numbers from a text file with re?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Counting all the numbers from a text file with re?



I am with the basics of RE, I need open a file with a lot of lines, take only the numbers and shows the average. This is my poor try:


import re

try:
ufile = open(input('What file are you using? '))
except:
print('File don't founded.')
exit()

lnumbers =

for line in ufile:
numbers = re.findall('([0-9.]+) ', line)
if len(numbers) > 0:
lnumbers.append(numbers)



I don't know what to do next.




1 Answer
1



Assuming that a given number would never wrap around from one line to the next, then a slight modification of your code should work:


for line in ufile:
numbers = re.findall('[0-9]+(.[0-9]+)?', line)
for number in numbers:
lnumbers.append(numbers)

if len(lnumbers) > 0:
print sum(lnumbers) / len(lnumbers)
else:
print "no numbers were found"





'1.....2' is a number?
– G_M
4 mins ago




'1.....2'





@G_M Fine. I fixed it.
– Tim Biegeleisen
3 mins ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived