【问题标题】:How to remove dash/ hyphen from each line in .txt file如何从 .t​​xt 文件的每一行中删除破折号/连字符
【发布时间】:2022-07-02 15:24:57
【问题描述】:

我编写了一个小程序,将书本扫描的页面转换为 .txt 文件。在某些行上,单词被移到另一行。我想知道这是否可以删除破折号并将它们与下面一行中的音节合并?

例如:

effects on the skin is fully under-
stood one fights

到:

 effects on the skin is fully understood
 one fights

或:

effects on the skin is fully 
understood one fights

或者类似的东西。只要是连接的。 Python是我的第三种语言,到目前为止我什么都想不出来,所以也许有人会给我提示。

编辑: 关键是最后一个符号,如果是破折号,将被删除并与下面的其余单词合并

【问题讨论】:

  • 我不明白带破折号的行和从您的示例中合并后的行如何。你有示例代码来向我们展示你到目前为止所做的事情吗?
  • 谢谢 - 您想要的结果与您给出的预期输出相矛盾。当您“与下面的其余单词合并”时,带有破折号的第二行和第三行对我来说没有意义。您能否修改您的示例以使用英语中的实际单词?
  • 我不关心它会如何合并,例如如果 n 行中的最后一个单词是“remov-”并且在 n+1 行中是“ing”,我想合并它
  • 我问所有这些问题的原因是社区更容易真正给你答案。目前还不清楚。
  • 我们不是来给你写代码的,你试过什么?

标签: python python-3.x replace txt


【解决方案1】:

这是一个逐行获取输入的生成器。如果它以- 结尾,它会提取最后一个单词并将其保留到下一行。然后它会从前一行与当前行结合产生任何保留的单词。

要将结果组合回单个文本块,您可以 join 它与您选择的行分隔符:

source = """effects on the skin is fully under-
stood one fights
check-out Daft Punk's new sin-
le "Get Lucky" if you hav-
e the chance. Sound of the sum-
mer."""

def reflow(text):
    holdover = ""
    for line in text.splitlines():
        if line.endswith("-"):
            lin, _, e = line.rpartition(" ")
        else:
            lin, e = line, ""
        yield f"{holdover}{lin}"
        holdover = e[:-1]

print("\n".join(reflow(source)))
""" which is:
effects on the skin is fully
understood one fights
check-out Daft Punk's new
single "Get Lucky" if you
have the chance. Sound of the
summer.
"""

逐行读取一个文件并直接写入一个新文件:

def reflow(infile, outfile):
    with open(infile) as source, open(outfile, "w") as dest:
        holdover = ""
        for line in source.readlines():
            line = line.rstrip("\n")
            if line.endswith("-"):
                lin, _, e = line.rpartition(" ")
            else:
                lin, e = line, ""
            dest.write(f"{holdover}{lin}\n")
            holdover = e[:-1]

if __name__ == "__main__":
    reflow("source.txt", "dest.txt")

【讨论】:

  • lin, _, e = line.rpartition有点自豪。感觉就像我做了一个弱双关语。
  • 做一个非常好的功能,它完美地工作。但是,我有一个关于上传文件的问题。我什么时候做: with open("test.txt") as f: contents = f.readlines() print("\n".join(reflow(contents))) 用行列表中的文件替换我,有什么方法可以加载文件以使用您的功能?
  • @Student111 我现在展示了如何从一个文件读取并写入另一个文件:)
  • 太完美了!
【解决方案2】:

这是一种方法

with open('test.txt') as file:
    combined_strings = []
    merge_line = False
    for item in file:
        item = item.replace('\n', '') # remove new line character at end of line
        if '-' in item[-1]:  # check that it is the last character
            merge_line = True
            combined_strings.append(item[:-1])
        elif merge_line:
            merge_line = False
            combined_strings[-1] = combined_strings[-1] + item
        else:
            combined_strings.append(item)

【讨论】:

    【解决方案3】:

    如果您只是将行解析为字符串,那么您可以利用 .split() 函数来移动这些类型的项目

    words = "effects on the skin is fully under-\nstood one fights"
    #splitting among the newlines
    wordsSplit = words.split("\n")
    #splitting among the word spaces
    for i in range(len(wordsSplit)):
        wordsSplit[i] = wordsSplit[i].split(" ")
    #checking for the end of line hyphens
    for i in range(len(wordsSplit)):
        for g in range(len(wordsSplit[i])):
            if "-" in wordsSplit[i][g]:
                #setting the new word in the list and removing the hyphen
                wordsSplit[i][g] = wordsSplit[i][g][0:-1]+wordsSplit[i+1][0]
                wordsSplit[i+1][0] = ""
    #recreating the string
    msg = ""
    for i in range(len(wordsSplit)):
        for g in range(len(wordsSplit[i])):
            if wordsSplit[i][g] != "":
                msg += wordsSplit[i][g]+" "
    

    它的作用是由通常出现连字符的换行符分开。然后它按单词将它们拆分成一个较小的数组。然后检查连字符,如果找到,则将其替换为单词列表中的下一个短语,并将该单词设置为空。最后,它将字符串重构为一个名为 msg 的变量,如果拆分数组中的值是空字符串,它不会添加空格。

    【讨论】:

      【解决方案4】:

      怎么样

      import re
      
      a = '''effects on the skin is fully under-
      stood one fights'''
      
      re.sub(r'-~([a-zA-Z0-9]*) ', r'\1\n', a.replace('\n', '~')).replace('~','\n')
      

      说明

      a.replace('\n', '~') 使用 (~ 而不是 \n - 如果要在文本中使用 ~ 字符,则需要选择其他字符串。)

      -~([a-zA-Z0-9]*) 正则表达式然后选择我们要使用 () 反向引用更改的所有字符串,将其保存到 re.sub 内存。使用 '\1\n' 稍后会重新调用它。

      .replace('~','\n') 最终将所有剩余的~ 字符替换为换行符。

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 2014-09-10
        • 2016-10-07
        • 2023-01-23
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        相关资源
        最近更新 更多