python - 如何从多个txt文件中删除多个字符
问题描述
我正在尝试编写一个脚本来自动执行从 txt 文件中删除字符的简单任务,并且我想用相同的名称保存它但没有字符。我有多个 txt 文件:例如 1.txt、2.txt ... 200.txt,存储在一个目录(文档)中。我有一个包含要删除的字符的 txt 文件。一开始我想将我的 chars_to_remove.txt 与我所有的不同文件(1.txt、2.txt...)进行比较,但我可以找到一种方法。相反,我创建了一个包含我想要删除的所有字符的字符串。
假设我在 1.txt 文件中有以下字符串:
2020 年 3 月、2019 年和 2018 年马德里和巴塞罗那(西班牙)的平均浓度α、最大值比率β和由于封锁Δ导致的二氧化氮减少。
我想从字符串中删除α
,β
和chars 。Δ
这是我的代码。
import glob
import os
chars_to_remove = '‘’“”|n.d.…•∈αβδΔεθϑφΣμτσχ€$∞http:www.←→≥≤<>▷×°±*⁃'
file_location = os.path.join('Desktop', 'Documents', '*.txt')
file_names = glob.glob(file_location)
print(file_names)
for f in file_names:
outfile = open(f,'r',encoding='latin-1')
data = outfile.read()
if chars_to_remove in data:
data.replace(chars_to_remove, '')
outfile.close()
该变量data
在每次迭代中存储 txt 文件中的所有内容。我想检查chars_to_remove
字符串中是否有并用replace()
函数将其删除。我尝试了这里和这里建议的不同方法,但没有成功。
另外,我尝试将其作为列表进行比较:
chars_to_remove = ['‘','’','“','”','|','n.d.','…','•','∈','α','β','δ','Δ','ε','θ','ϑ','φ','Σ','μ','τ','σ','χ','€','$','∞','http:','www.','←','→','≥','≤','<','>','▷','×','°','±','*','⁃']
但比较时出现数据类型错误。
任何进一步的想法将不胜感激!
解决方案
它可能没有那么快,但为什么不使用正则表达式来删除字符/短语呢?
import re
pattern = re.compile(r"(‘|’|“|”|\||n.d.|…|•|∈|α|β|δ|Δ|ε|θ|ϑ|φ|Σ|μ|τ|σ|χ|€|$|∞|http:|www.|←|→|≥|≤|<|>|▷|×|°|±|\*|⁃)")
result = pattern.sub("", 'Mean concentrations α, maximum value ratio β and reductions in NO2 due to the lockdown Δ, March 2020, 2019 and 2018 in Madrid and Barcelona (Spain).')
print(result)
输出
Mean concentrations , maximum value ratio and reductions in NO2 due to the lockdown , March 2020, 2019 and 2018 in Madrid and Barcelona (Spain).
推荐阅读
- matlab - 在 simscape 多体中建模 segway 机器人
- spring-boot - Spring Boot - 本地化到达自定义(DWR)AbstractController 的请求,本地化子线程,LocaleResolver 与 LocaleChangeInterceptor
- python - 如何将二维 numpy 数组中的所有数字转换为字符串?
- spring-boot - Spring Boot Maven 插件 > 2.4.x 构建镜像在 GitLab 注册表上发布
- sql-server - 无法使用特殊主体 'sa' - ant sql 任务
- html - 调整浏览器大小时,我的 div 容器溢出
- java - java.sql.SQLSyntaxErrorException: ORA-01797: 此运算符后面必须跟 ANY 或 ALL
- flutter - Flutter,Bloc,为什么MapEventToState中只使用Stream
- react-native - 没有幻灯片动画的介绍滑块
- excel - 将参数作为 VBA 中的数组传递给工作表函数