首页 > 解决方案 > 消除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'进行模式化。如果我的问题和我的语言错误不能说清楚,请原谅。我感谢大家的帮助。对每个人来说都是美好的一天!

标签: python

解决方案


我不知道您问题的全部范围,但到目前为止,您提供的信息很少。你可以这样做:

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

推荐阅读