【问题标题】:Python How do I merge hyphenated words with newlines?Python如何将连字符与换行符合并?
【发布时间】:2017-09-25 18:43:57
【问题描述】:
I want to say that Napp Granade
serves in the spirit of a town in our dis-
trict of Georgia called Andersonville.

我有数千个包含上述数据的文本文件,并且单词已使用连字符和换行符进行换行。

我要做的是删除连字符并将换行符放在单词的末尾。如果可能的话,我不想删除所有带连字符的单词,只删除那些位于行尾的单词。

            with open(filename, encoding="utf8") as f:
              file_str = f.read()


            re.sub("\s*-\s*", "", file_str)

            with open(filename, "w", encoding="utf8") as f:
              f.write(file_str)

上面的代码不起作用,我尝试了几种不同的方法。

我想浏览整个文本文件并删除所有表示换行符的连字符。如:

I want to say that Napp Granade
serves in the spirit of a town in our district
of Georgia called Andersonville.

任何帮助将不胜感激。

【问题讨论】:

  • 连字符是否总是在行尾,或者换行符之前是否还有空格?

标签: python regex python-3.x


【解决方案1】:

您不需要使用正则表达式:

filename = 'test.txt'

# I want to say that Napp Granade
# serves in the spirit of a town in our dis-
# trict of Georgia called Anderson-
# ville.

with open(filename, encoding="utf8") as f:
    lines = [line.strip('\n') for line in f]
    for num, line in enumerate(lines):
        if line.endswith('-'):
            # the end of the word is at the start of next line
            end = lines[num+1].split()[0]
            # we remove the - and append the end of the word
            lines[num] = line[:-1] + end
            # and remove the end of the word and possibly the 
            # following space from the next line
            lines[num+1] = lines[num+1][len(end)+1:]

    text = '\n'.join(lines)

with open(filename, "w", encoding="utf8") as f:
    f.write(text)


# I want to say that Napp Granade
# serves in the spirit of a town in our district
# of Georgia called Andersonville.

但你当然可以,而且更短:

with open(filename, encoding="utf8") as f:
    text = f.read()

text = re.sub(r'-\n(\w+ *)', r'\1\n', text)

with open(filename, "w", encoding="utf8") as f:
        f.write(text)

我们查找- 后跟\n,并捕获以下单词,即拆分单词的结尾。
我们将所有内容替换为捕获的单词,后跟换行符。

不要忘记使用原始字符串进行替换,以便正确解释 \1

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2020-10-06
    • 2010-09-29
    相关资源
    最近更新 更多