[英]Matching characters after a certain word and stop matching before this same word
[英]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.