python - 消除txt文件中的音节分隔
问题描述
首先,我想解释一下,由于这是我的第一篇文章,我在发布我的问题之前做了很多研究,正如这个优秀平台的问答中所建议的那样。我提出的第二点是我不是 python 专家。事实上,我只是这个伟大的编程语言的爱好者。好吧,我正在尝试修复一个相对较大的 txt 文件。问题的重点是纠正所引用文件中存在的大量音节分离。在我的研究中,我发现了一些与我的问题相似的文章,这甚至帮助我从不同的角度思考。在这些文章中,我可以强调一些,例如:
使用 grep:
grep -v '^$' test1.txt > test2.txt
使用文件输入:
导入 fileinput for line in fileinput.FileInput("file",inplace=1): if line.rstrip(): print line
但是,不幸的是,我的问题更具体。在我的 txt 文件中有很多音节分隔符。谢天谢地,它们都是这样标准化的:
example_of_w'-'
秩序
我的目标是通过一些 python 脚本来纠正/消除所有文件分隔,如下例所示:
脚本之前:
example_of_w'-'
秩序
脚本后:
example_of_word
请注意,音节分隔使用-和'space'进行模式化。如果我的问题和我的语言错误不能说清楚,请原谅。我感谢大家的帮助。对每个人来说都是美好的一天!
解决方案
我不知道您问题的全部范围,但到目前为止,您提供的信息很少。你可以这样做:
a = "example_of_w- ord has to be interest- ing"
# replace of occurrences of first argument with the second argument
print(a.replace("- ", ""))
输出:
example_of_word has to be interesting
编辑:
如果要对txt
文件中的所有行执行此操作,可以执行以下操作:
这是的内容sy.txt
:
example_of_word 必须很有趣。避难所或卸货区以离开活动场地。避难所或卸货区以离开活动场地。example_of_word 必须很有趣。河里的水很棒
这是同一文件夹中的脚本,而不是sy.txt
:
output = ""
replaceParameter = "- "
with open("sy.txt") as f:
for line in f:
output += line.replace(replaceParameter, "")
print(output)
输出将是:
example_of_word 必须很有趣。避难或卸货区,以退出活动场地。避难或卸货区,以退出活动场地。example_of_word 必须很有趣。河里的水很棒
如您所见,我打开了一个文件,然后循环遍历其中的所有行并将 替换replaceParameter = "- "
为空字符串。
编辑2:
这适用于行尾的情况:
output = ""
replaceParameter = "- "
with open("sy.txt") as f:
for line in f:
output += line
output = output.replace("\n- ", "")
output = output.replace("-\n ", "")
output = output.replace("- \n", "")
output = output.replace(replaceParameter , "")
print(output)
尝试一下input
:
example_of_w- ord has to be interest- ing. refuge or dis- charge area to exit the event grounds.
refuge or dis- charge area to exit the event grounds. example_of_w- ord has to be interest- ing.
wa- ter in the riv- er is wonder- ful. refuge or dis- charge area to exit the event grounds ref-
uge or dis- charge area to exit the event grounds. refuge or dis- charge area to exit the linebr
- eaks
和output
:
example_of_word has to be interesting. refuge or discharge area to exit the event grounds. refuge or discharge area to exit the event grounds. example_of_word has to be interesting. water in the river is wonderful. refuge or discharge area to exit the event grounds refuge or discharge area to exit the event grounds. refuge or discharge area to exit the linebreaks
推荐阅读
- docker - 错误 pipeline/output.go:100 无法连接到 backoff(async(tcp://logstash:5044)) - ELK Filebeat .NET Core 3.1 Docker
- node.js - Nuxt 和 Docker:在 nuxt.config.js 中指定服务器 - 甚至默认 - 阻止访问 localhost?
- android-studio - Android Studio 未找到某些方法和字段的用法
- c# - Entity Framework Core 使用 Dbset 而没有 T
- nginx - 在 Nginx 上服务 Jekyll 博客
- python - 在 Vispy 中标准化可缩放时间序列图的比例
- c# - 将纯文本转换为在 p 标签内包含 i 标签
- python - 仅当我们匹配要查找的两个单词时,才提取第一个匹配项和第二个匹配项之后的单词(直到到达逗号)
- c++ - 计算 6 x 6 矩阵中每个沙漏的沙漏总和(其中条目只能从 0 到 9),然后打印最大沙漏总和
- css - 表单元素忽略正文 CSS