繁体   English   中英

在一个单词之前和之后输出字符,然后写入文件

[英]output characters before and after a word then write to file

我正在尝试获取此代码以在特定单词之前找到30个单词,之后找到30个单词。 然后我希望它将我的输出写入新文件。 我似乎无法弄清楚我在做什么错,因为我是python的新手。 任何建议都值得欢迎。

def extract_text(file_name, to_find):
    file_in = open('School.txt', 'r')

    all_lines = file_in.readlines()
    file_in.close()

    new_text = all_text.replace ('\n',  '|')

    width = 30



to_find = 'boy'
new_text = all_text.replace ('\n',  '|')
while new_text.find(to_find) != -1:
    start = all_text.find(to_find)
    begin = start - width
    end = start + len(to_find) + width



    print(new_text[begin:end])
    out_put = new_text[begin:end]

    f = open("School_boy.txt","w")
    f.write(out_put)

    f.close()

对于文本解析,我建议使用正则表达式:

import re

# Read the File
with open("file.txt", "r") as file:
    text = file.read()

# replace newline with blank
text.replace('\n', '')

# parse the text
result = re.findall(r'(?P<before>\w+ ){30}target(P?<after>\w+ ){30}', text)

从那里开始,之前的所有30个单词都在称为“之前”的组中,而之后的所有30个单词都在称为目标单词的“之后”的组中。 RegEx可以是特定的,也可以是通用的,具体取决于所使用的模式。 例如,上面的代码只允许在单词后留一个空格,而不能使用标点符号。 有关python regex的指南: https : //docs.python.org/3/howto/regex.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM