使用Python在一个文件中使用多个re.sub()调用
我有一个包含大量随机字符串的文件。有些模式我不想删除,所以我决定使用正则表达式来检查它们。到目前为止,这段代码完全符合我的要求:使用Python在一个文件中使用多个re.sub()调用,python,regex,Python,Regex,我有一个包含大量随机字符串的文件。有些模式我不想删除,所以我决定使用正则表达式来检查它们。到目前为止,这段代码完全符合我的要求: #!/usr/bin/python import csv import re import sys import pdb f=open('output.csv', 'w') with open('retweet.csv', 'rb') as inputfile: read=csv.reader(inputfile, delimiter=',')
#!/usr/bin/python
import csv
import re
import sys
import pdb
f=open('output.csv', 'w')
with open('retweet.csv', 'rb') as inputfile:
read=csv.reader(inputfile, delimiter=',')
for row in read:
f.write(re.sub(r'@\s\w+', ' ', row[0]))
f.write("\n")
f.close()
f=open('output2.csv', 'w')
with open('output.csv', 'rb') as inputfile2:
read2=csv.reader(inputfile2, delimiter='\n')
for row in read2:
a= re.sub('[^a-zA-Z0-9]', ' ', row[0])
b= str.split(a)
c= "+".join(b)
f.write("http://www.google.com/webhp#q="+c+"&btnI\n")
f.close()
问题是,我想避免打开和关闭一个文件,因为如果我需要检查更多的模式,这可能会变得混乱。如何对同一个文件执行多个re.sub()调用,并将其写入一个包含所有替换的新文件
谢谢你的帮助 在当前行上一次性应用所有替换:
with open('retweet.csv', 'rb') as inputfile:
read=csv.reader(inputfile, delimiter=',')
for row in read:
text = row[0]
text = re.sub(r'@\s\w+', ' ', text)
text = re.sub(another_expression, another_replacement, text)
# etc.
f.write(text + '\n')
请注意,使用csv.reader(…,delimiter='\n')
打开文件听起来非常像是将该文件视为一系列行;您可以在文件上循环:
with open('output.csv', 'rb') as inputfile2:
for line in inputfile2:
csv.reader(…,分隔符='\n')
?为什么不逐行读取文件呢<代码>对于inputfile2中的行:就足够了。。