Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

nltk - Python - Extracting sentences from paragraphs

I am new to python & can use some help:

This is just a sample :

I have a dictionary (with same key values repeating inside a list:

list_dummy = [{'a': 1, 'b':"The house is great. I loved it.",'e':"loved,the"}, {'a': 3, 'b': "Building is white in colour. I liked it.",'e':"colour"}, {'a': 5, 'b': "She is looking pretty. She is in my college",'e':"pretty"}]

'b' - consists of body text 'e' - consists of words(can be more than one)

I want to extract sentences out of 'b' which contains either one or more words from 'e' in them.

I need to first split the text into sentences by sent_tokenize & than need to extract. Sent_tokenize takes only string as an input. How to proceed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well I can't seem to get the nltk module working to test but as long as sent_tokenize() returns a list of sentence strings something like this I think should do what you're hoping (if I understood correctly):

ans = []
for d in list_dummy:
    tmp = sent_tokenize(d['b'])
    s = [x for x in tmp if any(w.upper() in x.upper() for w in d['e'].split(","))]
    ans += s

This assumes that e will always be a comma separated list and that you're interested in case insensitive searching. The ans variable will just be a flat list of sentences that contain a word from the 'e' value in the dictionary.

EDIT

If you prefer using regular expressions you could use the re module:

import re
ans = []
for d in list_dummy:
    b = sent_tokenize(d['b'])
    e = d['e'].split(",")
    rstring = ".*" + "|".join(e) + ".*"
    r = re.compile(rstring)
    ans.append([x for x in b if r.match(x)])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...