从本地文本文件中抓取相关的文本段落

2024-09-28 03:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一段python代码,能够刮文本的相关部分。假设我有一组单词,当它遇到其中一个单词时,它会在找到单词的句子前后刮1到2个句子。 然后它应该打印下面的文本以便可以复制。你知道吗

例如,请参阅下面的文本。让我们说相关的词是“简单”。它在第3行检测到“simple”。所以它刮到了2,3和4号线。你知道吗

美丽胜于丑陋。显性比隐性好。简单胜于复杂。复杂总比复杂好。可读性很重要。你知道吗

变成->

“显性比隐性好。简单胜于复杂。复杂总比复杂好

我相信代码的想法很简单。但是我不知道如何做到这一点。你知道吗

import re

caps = "([A-Z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov)"

def split_into_sentences(text):
    text = " " + text + "  "
    text = text.replace("\n"," ")
    text = re.sub(prefixes,"\\1<prd>",text)
    text = re.sub(websites,"<prd>\\1",text)
    if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
    text = re.sub("\s" + caps + "[.] "," \\1<prd> ",text)
    text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
    text = re.sub(caps + "[.]" + caps + "[.]" + caps + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
    text = re.sub(caps + "[.]" + caps + "[.]","\\1<prd>\\2<prd>",text)
    text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
    text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
    text = re.sub(" " + caps + "[.]"," \\1<prd>",text)
    if "\"" in text: text = text.replace(".\"","\".")
    if "!" in text: text = text.replace("!\"","\"!")
    if "?" in text: text = text.replace("?\"","\"?")
    text = text.replace(".",".<stop>")
    text = text.replace("?","?<stop>")
    text = text.replace("!","!<stop>")
    text = text.replace("<prd>",".")
    sentences = text.split("<stop>")
    sentences = sentences[:-1]
    sentences = [s.strip() for s in sentences]
    return sentences

relevantwords = ["refugees","conflicts","mobility", "rights", "presence", "freedom", "immigrants", "politics", "political"] 


    for i in range(20):

    file = open("text"+str(i)+".txt", "r")
    data = file.readlines()

    for line in split_into_sentences(str(data)):
        if "relevantwords" in line:
            print str(i–1,i,i+1)
            print str(line).encode('UTF-8')
            print "\n"

Tags: textin文本reifsentencescaps单词
1条回答
网友
1楼 · 发布于 2024-09-28 03:21:17

我会给你一个粗略的大纲的一些代码,如果你有困难,实现它,请随时张贴你的代码,我会很乐意帮助你在哪里你有问题!你知道吗

您需要:

  1. 将文件读入程序中的字符串
  2. 通过拆分字符'.'将字符串拆分为句子。注意,如果你有像“mr.”这样的缩写,它会认为这是一个句子的结尾。你知道吗
  3. 现在重复句子列表,在每次迭代中,执行以下操作:
    • 检查单词是否在句子i中。如果是这样,就打印出i-1ii+1等句子
    • 或者,如果不想打印出来,可以将它们添加到开始时创建的列表中

如果你有任何具体的问题,如何实施这一点,让我知道!你知道吗

相关问题 更多 >

    热门问题