![](/img/trans.png)
[英]extracting the 2 words before, the actual word, and the 2 strings after a specific string in python?
[英]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.