我是python的新手,我正在尝试扫描文件并将我找到的任何整数转换为值1。 我可以使用正则表达式吗?或某种我可以使用的功能
答案 0 :(得分:1)
def numbers_with_zero(file_):
import re
# Note:current regex will convert floats and ints to 0
# if one wants to just convert ints, and convert them to 1
# do line = re.sub(r'[-+]?\d+',r'1',line)
file_contents = []
# read file, change lines
with open(file_, 'r') as f:
for line in f:
# this regex should take care of ints, floats, and sings, if any
line = re.sub(r'[-+]?\d*\.\d+|\d+',r'0',line)
file_contents.append(line)
# reopen file and write changed lines back
with open(file_, 'w') as f:
for line in file_contents:
f.write(line)
答案 1 :(得分:0)