这是我的问题。我有一个示例文本文件,我在其中通过抓取各种 html 页面来存储文本数据。该文本包含有关各种事件及其时间和地点的信息。我想获取这些位置的坐标。我不知道如何在 python 中做到这一点。我正在使用 nltk 来识别此示例文本中的命名实体。这是代码:
import nltk
with open('sample.txt', 'r') as f:
sample = f.read()
sentences = nltk.sent_tokenize(sample)
tokenized_sentences = [nltk.word_tokenize(sentence) for sentence in sentences]
tagged_sentences = [nltk.pos_tag(sentence) for sentence in tokenized_sentences]
chunked_sentences = nltk.batch_ne_chunk(tagged_sentences, binary=True)
#print chunked_sentences
#print tokenized_sentences
#print tagged_sentences
def extract_entity_names(t):
entity_names = []
if hasattr(t, 'node') and t.node:
if t.node == 'NE':
entity_names.append(' '.join([child[0] for child in t]))
else:
for child in t:
entity_names.extend(extract_entity_names(child))
return entity_names
entity_names = []
for tree in chunked_sentences:
# Print results per sentence
# print extract_entity_names(tree)
entity_names.extend(extract_entity_names(tree))
# Print all entity names
#print entity_names
# Print unique entity names
print set(entity_names)
示例文件是这样的:
考文特花园的波希米亚人
时间:2013 年 1 月 18 日(不同日期),晚上 7 点 30 分地点:考文特花园 (Covent Garden)
伦敦,约翰·科普利 (John Copley) 皇家歌剧院长期流行的作品
普契尼的《艺术家生涯》在本季两场演出中首次上演,
正好在圣诞节期间。马克·埃尔德爵士指挥罗兰多
Villazón 饰演 Rodolfo,Maija Kovalevska 饰演 Mimì。咪咪遇见诗人
鲁道夫(德米特罗·波波夫于 1 月 5 日至 18 日演唱该角色)感冒了
巴黎拉丁区的圣诞夜。在黑暗中摸索
她的蜡烛熄灭后,他们坠入爱河。鲁道夫与
另外三个小伙子:哲学家科林(Nahuel di Pierro/Jihoon Kim)
1 月 18 日),音乐家 Schaunard(David Bizic)和画家 Marcello
(奥敦·伊弗森饰),爱上了穆塞塔(斯特凡妮娅·多夫汉饰)。夫妻俩
分手,歌剧以悲剧结束,鲁道夫发现咪咪死于
在冰冷的阁楼里消费。
我想从此文本中获取伦敦考文特花园的坐标。我该怎么做 ?
自 2013 年 9 月起,Google 地图 API v2不再有效。这是很棒的 @jimhark 代码的更新版本,适用于 API v3(我省略了__main__
part):
import urllib
import simplejson
googleGeocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?'
def get_coordinates(query, from_sensor=False):
query = query.encode('utf-8')
params = {
'address': query,
'sensor': "true" if from_sensor else "false"
}
url = googleGeocodeUrl + urllib.urlencode(params)
json_response = urllib.urlopen(url)
response = simplejson.loads(json_response.read())
if response['results']:
location = response['results'][0]['geometry']['location']
latitude, longitude = location['lat'], location['lng']
print query, latitude, longitude
else:
latitude, longitude = None, None
print query, "<no results>"
return latitude, longitude
See 官方文档获取完整的参数列表和附加信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)