从文本中提取特定信息
我想从一个文本文件中获取一些数据。我决定使用自然语言工具包来实现,但如果有更好的方法,我也乐意听听。
这里有个例子:
我需要从纽约(NY)飞往旧金山(CA)。
从这段文字中,我想提取出出发地和目的地的城市和州。
这是我目前的进展:
import nltk
from nltk.text import *
from nltk.corpus import PlaintextCorpusReader
def readfiles():
corpus_root = 'C:\prototype\emails'
w = PlaintextCorpusReader(corpus_root, '.*')
t = Text(w.words())
print "--- to ----"
print t.concordance("to")
print "--- from ----"
print t.concordance("from")
我可以从某个输入(在我的情况下是文件)中读取文本,然后使用一致性方法来找到所有的用法。我想提取出在“to”和“from”后面的城市和州的信息。
我的问题是,如何才能最好地查看“to”和“from”后面的文本呢?
1 个回答
1
也许你可以考虑一行一行地读取文件?
这样做的话,可以用这么简单的方式:
cityState = dataAfterTo.split(",")
city = cityState[0]
state = cityState[1].split()[0]
当然,如果你处理的是用户生成的内容,那就另当别论了。