【问题标题】:printing 5 words before and after a specific word in a file in python在python文件中的特定单词之前和之后打印5个单词
【发布时间】:2016-07-11 17:24:00
【问题描述】:

我有一个文件夹,其中包含一些其他文件夹,这些文件夹包含一些文本文件。 (语言是波斯语)。我想在关键字之前和之后打印 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])

我的期望是这样的:

词词词词词词词词词词词词词

每个句子换行。

【问题讨论】:

  • 如果关键字是第三个单词怎么办?我们之前只输出 3 个,还是包括前几行的 5 个?
  • 在这种情况下,只有 3 个之前

标签: python nlp


【解决方案1】:

试试这个。它分裂了单词。然后它会计算前后显示的数量(最少剩余多少,最多 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])

【讨论】:

  • 非常感谢大家。
  • @suneye 如果解决了您的问题,请接受带有向下箭头下方灰色勾号的选项。
  • 当然这里所有的答案都是可以接受的。谢谢
  • @suneye 如果您单击其中一个上的勾号,它会将问题标记为已解决
【解决方案2】:

您需要根据关键字的索引获取单词索引。您可以使用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

【讨论】:

    【解决方案3】:
    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))]))
    

    假设关键字必须是一个精确的单词。

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多