import re
digit_count=0
number_count = 0
numbers = []
count=0
with open ("letters_and_numbers.txt") as f:
for line in f.readlines():
sub_strs = line.rstrip().split("-")
file_words = re.split(r"[a-zA-Z\W]",line.rstrip())
for word in file_words:
if word.isdigit():
digit_count += len(word)
number_count += 1
numbers.append(word)
foundNeg=False
for i in range(1, len(sub_strs)):
if str(sub_strs).startswith(word):
foundNeg == True
count-=int(word)
else:
foundNeg==False
count+=int(word)
print "digits:",digit_count
print "amount of numbers:",number_count
print "numbers:",numbers
print "total:",count
I am trying to get the above program to work but it only can if i can split by regex whitespaces except negative signs.How do I fix it???
NEVER MIND I FIGURED IT OUT
Here is my answer.It is the code I used and it worked even when there were no spaces between numbers and letters.
import re
digit_count=0
number_count = 0
numbers = []
count=0
with open ("letters_and_numbers.txt") as f:
for line in f.readlines():
sub_strs = line.rstrip().split("-")
for i in range(0, len(sub_strs)):
file_words = re.split(r"[a-zA-Z\W]",sub_strs[i])
for word in file_words:
if word.isdigit():
digit_count += len(word)
number_count += 1
if i >=1 and sub_strs[i].startswith(word):
count-=int(word)
digit_count+=1
numbers.append("-")
numbers.append(word)
else:
count+=int(word)
numbers.append(word)
print "digits:",digit_count
print "amount of numbers:",number_count
print "numbers:",numbers
print "total:",count
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.