0

当“用户输入”匹配文档“Updated_Word.doc”中的单词时,字符串加上以下两行将写入名为 word_file.txt 的单独 txt 文件中。我遇到的问题是当我打开 txt 文件时,它看起来像这样:

Match Word

Line 1

Line 2

我知道这可能是一个简单的解决方案,但我正在努力寻找一种方法将这些行写入 txt 文件而没有换行符。例子:

Match Word
Line 1
Line 2

这是执行匹配并写入 txt 文件的代码部分:

def grabWord():
string = input('Input Word Name:\n')
user_input = re.compile(string)
x = user_input.findall('Updated_Word.doc')
    with open('Updated_Word.doc', mode='r') as infile:
    for line in infile:
        if string in line:
            print('Found Match!')
            with open('Word_file.txt', mode='a') as outfile:
                if line.strip():
                    x = [line, next(infile), next(infile), next(infile), next(infile)]
                    outfile.writelines(x)

任何帮助,将不胜感激。

4

1 回答 1

1

似乎您正在编写找到的行加上接下来的 4 行,其中两行只是换行符。

if line.strip():
    x = [line, next(infile), next(infile), next(infile), next(infile)]

一个快速而肮脏的解决方法是过滤您的最终结果,删除那些原本为空的行:

if line.strip():
    x = [line, next(infile), next(infile), next(infile), next(infile)]
    x = (list(filter(lambda element: element.strip(), x)))
    outfile.writelines(x)

另一种方法是搜索接下来的两个非空行:

if line.strip():
    two_next_lines = []

    try:
        while len(two_next_lines) < 2:
            current = next(line)

            if current.strip():
                two_next_lines.append(current)
    except StopIteration:
        # there are not enough next lines matching your requirements
        pass


    x = [line] + [two_next_lines]
    outfile.writelines(x)
于 2020-06-17T01:17:47.457 回答