簡體   English   中英

在python文件中的特定單詞之前和之后打印5個單詞

[英]printing 5 words before and after a specific word in a file in python

我有一個包含其他文件夾的文件夾,這些文件夾包含一些文本文件。 (語言是波斯語)。 我想在一個關鍵字的前后分別打印5個單詞,並在其中包含該關鍵字。 我編寫了代碼,但是在行的開頭和結尾給出了5個單詞,而不是關鍵字周圍的單詞。 我該如何解決?

提示:我只寫了與上述問題相關的代碼的結尾。 代碼的開頭與打開和規范化文件有關。

def c ():
y = "آرامش"
text= normal_text(folder_path) # the first function to open and normalize the files
for i in text:
    for line in i:
        if y in line:
            z = line.split()
            print (z[-6], z[-5],
                   z[-4], z[-3],
                   z[-2], z[-1], y,
                   z[+1], z[+2],
                   z[+3], z[+4],
                   z[+5], z[+6])

我期望的是這樣的:

單詞單詞單詞單詞單詞單詞單詞單詞單詞單詞單詞單詞

每個句子換行。

您需要根據關鍵字的索引獲取單詞索引。 您可以使用list.index()方法來獲取所需的索引,然后使用簡單的索引獲取所需的單詞:

for f in normal_text(folder_path):
    for line in f:
      if keyword in line:
          words = line.split()
          ins = words.index(keyword)
          print words[max(0, ind-5):min(ind+6, len(words))]

或者,作為一種更優化的方法,您可以使用生成器函數來生成單詞,作為迭代器,這在內存使用方面非常優化。

def get_words(keyword):
    for f in normal_text(folder_path):
        for line in f:
            if keyword in line:
                words = line.split()
                ins = words.index(keyword)
                yield words[max(0, ind-5):min(ind+6, len(words))]

然后,您可以簡單地遍歷結果以進行打印等。

y = "آرامش"
for words in get_words(y):
    # do stuff

嘗試這個。 它拆分單詞。 然后,它計算之前和之后要顯示的數量(剩余的數量最少,最多5個)並顯示它。

words = line.split()
if y in words:
    index = words.index(y)
    before = index - min(index, 5)
    after = index + min( len(words) - 1 - index, 5) + 1    
    print (words[before:after])
def c():
    y = "آرامش"
    text= normal_text(folder_path) # the first function to open and normalize the files
    for i in text:
        for line in i:
            split_line = line.split()
            if y in split_line:
                index = split_line.index(y)
                print (' '.join(split_line[max(0,index-5):min(index+6,le
n(split_line))]))

假設關鍵字必須是一個確切的詞。

暫無
暫無

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

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