2つのキーワードを定義した後、私の目標は次のとおりです。
非構造化テキストファイルの全内容を読む(1000行以上のテキスト)
コンテンツをループし、キーワードがヒットするたびにキーワードの左側に60文字をフェッチします
新しいテキストファイルの別々の行に各60文字の文字列を追加します
非構造化テキストファイルを読み取り、新しいテキストファイルに書き込むためのコードがあります。
私はトラブルになるコードの作成が午前求め、各キーワードをファイルの最後まで内容は、ループをフェッチします。
非常に簡単に、これが私がこれまでに持っているものです:
#read file, store in variable
content=open("demofile.txt", "r")
#seek "KW1" or "KW2", take 60 characters to the left, append to text file, loop
#open a text file, write variable contents, close file
file=open("output.txt","w")
file.writelines(content)
file.close()
このコードの中央部分についてサポートが必要です。たとえば、ソーステキストファイルに次のように記載されている場合:
「いくつかのテキスト、いくつかのテキスト、いくつかのテキスト、キーワード」
戻りたい:
「いくつかのテキスト、いくつかのテキスト、いくつかのテキスト、」
見つかった各キーワードの新しい行。
ありがとうございました。
result = []
# Open the file
with open('your_file') as f:
# Iterate through lines
for line in f.readlines():
# Find the start of the word
index = line.find('your_word')
# If the word is inside the line
if index != -1:
if index < 60:
result.append(line[:index])
else:
result.append(line[index-60:index])
その後result
、ファイルに書き込むことができます
複数の単語がある場合は、次のようにコードを変更できます。
words = ['waka1', 'waka2', 'waka3']
result = []
# Open the file
with open('your_file') as f:
# Iterate through lines
for line in f.readlines():
for word in words:
# Find the start of the word
index = line.find(word)
# If the word is inside the line
if index != -1:
if index < 60:
result.append(line[:index])
else:
result.append(line[index-60:index])
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加