问题描述
我是 python 新手,我正在尝试扫描文件并将我找到的任何整数转换为 1 的值。是否有我可以使用的正则表达式? 或某种我可以使用的功能
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)
2楼
Olle Muronde,您可以在找到有关如何重写文件中行的信息。
文件的每一行都可以被视为一个字符串,用其他符号替换某些符号的最简单方法是re.sub
函数来自。
我强烈建议您学习 Python 文档并更频繁地使用 google 或 stackoverflow 搜索,因为已经发布了很多好的答案。