如何在文本文件中多次出现的某些单词后提取3000个字符?

2024-06-01 13:28:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件:

"Accounting Principles. Negative Pledge Clauses . Clauses Restricting Subsidiary Distributions . Lines of Business......Accounting Principles: is defined in the definition of IFRS. Administrative Agent: SVB......In the event that any Accounting Principles (as defined below) shall occur and such change results......"

在此文件中,“会计原则”出现三次,“国际财务报告准则”出现一次。你知道吗

我试着在每个“会计原则”和“国际财务报告准则”后面提取3000个字符(或300个单词)。现在我只能提取“会计准则”第一次出现后的字符,并为“会计准则”和“国际财务报告准则”分别编写代码。因此,我的问题是如何在每次出现“会计原则”后提取3000个字符,以及如何编写一个代码,使我能够同时处理“会计原则”和“国际财务报告准则”,而不是使用两个单独的代码?你知道吗

非常感谢!你知道吗

我的代码如下:

import os
sourcepath=os.listdir('try/')
for filename in sourcepath:
    inputfile='try/'+filename
    with open(inputfile, 'r') as f:
        text=f.read()
        index=text.index('Accounting Principles')
        right=text[index: index+3000]
        print(right)

import os
sourcepath=os.listdir('try/')
for filename in sourcepath:
    inputfile='try/'+filename
    with open(inputfile, 'r') as f:
        text=f.read()
        index=text.index('IFRS')
        right=text[index: index+3000]
        print(right)

Tags: 代码textrightindexosfilenameaccounting国际
2条回答

您可以使用re.sub"Accounting Principles""IFRS"的任何位置创建一个标记,然后遍历整个\u字符串

marked_data = re.sub('Accounting\sPrinciples|IFRS', '*', open('filename.txt').read())
new_data = [marked_data[i:i+3000] for i in range(len(marked_data)-3000)]

这个程序查找“会计原则”或“国际财务报告准则”的每个实例,并打印匹配的字符串以及超出其结尾的30个字符。你知道吗

import re

with open('x.in') as fp:
    text = fp.read()

for m in re.finditer("Accounting Principles|IFRS", text):
    print(text[m.start():m.end()+30])

相关问题 更多 >