簡體   English   中英

獲取 python 文件中特定單詞前的 10 個單詞

[英]Get 10 words before a particular word in a file in python

我有一個文件,其中逐行包含句子。 我需要在特定單詞(不區分大小寫)之前得到 10 個單詞,但它也可以在前一行中。 例如:如果我想要單詞 ball 並且它是第二行的第四位,那么我需要該行中的 3 個單詞和前一行甚至之前的 7 個單詞。 我也想不出從前幾行中准確獲取 10 個單詞的方法。 這是我到目前為止所擁有的:


for line in file:
            # reading each word        
            for words in line.split():
                y = 'myword'.lower
                if y = words.lower:
                    index = words.index(y)
                    i = 0, z = 0
                    for words in line[i]:
                        sentence += words
                        if str(len(sentence.split()) != 10:
                        i--
                    
                    print(sentence)                                                       
                    
                    
                      

將整個文件轉換為單詞列表是可行的:

words_list = list()
with open('text.txt', 'r') as f:
    words_list = f.read().split()

ret = str()
for word in words_list:
  if 'even' == word:
    start_index = words_list.index(word) -10
    ret = ' '.join(words_list[start_index : words_list.index(word)+1])

print(ret)

您的代碼可能無法正常工作,因為lower()是一種方法,而不是屬性。 此外,考慮將您的單詞放在循環之外,這樣它就不會在每次迭代時都被創建。

如果您的代碼仍然無效,我創建了以下應該有效的代碼:

myword = "myword"
sentence = ""

split_sentence = s.split(" ")

for index, word in enumerate(split_sentence):
    # remove special characters
    if re.sub("[.!?,'@#$%^&*()\n]", "", word).lower() == myword:
        # make sure the start index is inbounds
        start_index = index-11 if index-11 > 0 else 0
        for word_index in range(start_index, start_index+10):
            sentence += f"{split_sentence[word_index]} "

print(sentence)

這應該創建一個包含 10 個詞的句子,這些詞指向您要查找的詞,包括標點符號。 如果您只需要單詞而不需要標點符號,那么這應該可以解決問題:

myword = "myword"
sentence = ""

# remove special characters
split_sentence = re.sub("[.!?,'@#$%^&*()\n]", "", s).split(" ")

for index, word in enumerate(split_sentence):
    if word.lower() == myword:
        # make sure the start index is inbounds
        start_index = index-11 if index-11 > 0 else 0
        for word_index in range(start_index, start_index+10):
            sentence += f"{split_sentence[word_index]} "

print(sentence)

不知道你的檔案怎么樣。 所以,我放了一個字符串來模擬它。 我的版本取之前的 10 個詞,如果沒有,取之前的所有詞,並給你一個最終列表,其中包含包含該詞的所有短語的所有詞。

def get_10_words(file, word_to_find):
file_10_words_list = []
cont = 0
for line in file.lower().split('\n'):
    new_line = line.split(' ')
    for c in range(10):
        new_line.insert(0, '')
    try:
        word_index = new_line.index(word_to_find.lower())
    except ValueError:
        print(f"Line {cont + 1} hasn't got {word_to_find.title()}")
    else:
        words_before_list = [new_line[element + word_index] for element in range(-10, 0)]
        words_before_list = [element for element in words_before_list if element != '']
        file_10_words_list.append(words_before_list)
    cont += 1
return file_10_words_list

if __name__ == '__main__':
words = get_10_words('This is the line one This is the line one This is the line one Haha\n'
                     'This is the line two This is the line two This is the line two How\n'
                     'This is the line tree Haha', 'Haha')

print(words)

如果我的代碼中有什么不清楚的地方,你可以在這里問我!

由於您標記 ,這里有一個帶有的命題。

#pip install spacy
#python -m spacy download en_core_web_sm
import spacy
​
with open("file.txt", "r") as f:
    text = f.read()
​
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
​
searchedWord = "StackOverflow"
​
occu = [i for i,word in enumerate(doc) if word.text == searchedWord]
​
out = []
for i in occu:
    if token.is_punct or token.is_space:
        i-=1
        w = [token.text for token in doc[i-4:i]]
        out.append(w)
    else:
        w = [token.text for token in doc[i-4:i]]
        out.append(w)

注意:在這個例子中,我們定位搜索到的單詞之前的 4 個單詞(同時跳過標點符號和空格)。結果將是一個嵌套列表,以處理該單詞在文本文件中出現多次的情況。 我們使用的是英語 model,但當然還有許多其他可用語言,請查看此處的列表。

Output:

print(out)
​
#[['A', 'question', 'from', 'Whichman'], ['An', 'answer', 'from', 'Timeless']]

使用的輸入/文本文件:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM