如何读取文件并找到所有以\d+\s 开头的匹配模式的行。并将写入空间替换为 , 。有些行包含英文字符。但有些线路是中国人的。我猜中文编码的书写空间与英文不同?
示例(text.txt)
asdfasdf
1 abcd
2 asdfajklsd
3 asdfasdf
4 ...
asdfasdf
66 ...
aasdfasdf
99 ...
100 中文
101 中文
102 asdfga
103 中文
我的测试代码:
with open('text.txt', 'r') as t:
with open('newtext.txt', 'w') as nt:
content = t.readlines()
for line in content:
okline = re.compile('^[\d+]\s')
if okline:
ntext = re.sub('\s', ',', okline)
nt.write(ntext)
最佳答案
同单re.subn()功能:
with open('text.txt', 'r') as text, open('newtext.txt', 'w') as new_text:
lines = text.read().splitlines()
for l in lines:
rpl = re.subn(r'^(\d+)\s+', '\\1,', l)
if rpl[1]:
new_text.write(rpl[0] + '\n')
<小时/>
这样做的主要优点是 re.subn
将返回一个元组 (new_string, number_of_subs_made)
,其中 number_of_subs_made
是指向的关键值到所需匹配行上进行的替换
关于Python 2.7 搜索行如果匹配模式并替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45008464/