Ans*_*kur 3 python google-maps nltk coordinates bing-maps
这是我的问题.我有一个示例文本文件,我通过爬行各种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)
Run Code Online (Sandbox Code Playgroud)
示例文件是这样的:
考文特花园的Labohème
时间:2013年1月18日(各个日期),晚上7点30分地点:伦敦考文特花园,约翰科普利常年受欢迎的皇家歌剧院出版的Puccini'sLabohème在本赛季两次中首次复活,恰逢圣诞节期间.马克·埃尔德爵士将RolandoVillazón指挥为Rodolfo,将Maija Kovalevska指定为Mimì.Mimì在巴黎的拉丁区迎接诗人鲁道夫(Dmytro Popov在1月5日和18日演唱)一个寒冷的平安夜.在她的蜡烛熄灭后,在黑暗中摸索,他们坠入爱河.Rodolfo与另外三位小伙子生活在一起:哲学家Colline(Nahuel di Pierro/Jihoon Kim,1月18日),音乐家Schaunard(David Bizic)和画家Marcello(Audun Iversen),他们喜欢Musetta(Stefania Dovhan).两个夫妻分手,歌剧以悲剧告终,因为鲁道夫发现米米在冰冷的阁楼里消费死亡.
我想从这段文本中获取伦敦考文特花园的坐标.我该怎么做 ?
自2013年9月起,Google Maps API v2 不再有效.这是伟大的@ jimhark代码的更新版本,适用于API v3(我遗漏了__main__部分):
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
Run Code Online (Sandbox Code Playgroud)
有关完整的参数列表和其他信息,请参阅官方文档.
你真的有两个问题:
我可以帮助解决第二个问题.(但请参阅下面的编辑,以获得有关第一个问题的帮助.)
使用旧的Google Maps API(仍在使用),您可以将地理编码降低到一行(一条丑陋的线):
def geocode(address):
return tuple([float(s) for s in list(urllib.urlopen('http://maps.google.com/maps/geo?' + urllib.urlencode({'output': 'csv','q': address})))[0].split(',')[2:]])
Run Code Online (Sandbox Code Playgroud)
这是可读的7行版本加上一些包装器代码(从命令行调用时记得将地址括在引号中):
import sys
import urllib
googleGeocodeUrl = 'http://maps.google.com/maps/geo?'
def geocode(address):
parms = {
'output': 'csv',
'q': address}
url = googleGeocodeUrl + urllib.urlencode(parms)
resp = urllib.urlopen(url)
resplist = list(resp)
line = resplist[0]
status, accuracy, latitude, longitude = line.split(',')
return latitude, longitude
def main():
if 1 < len(sys.argv):
address = sys.argv[1]
else:
address = '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
coordinates = geocode(address)
print coordinates
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
解析CSV格式很简单,但XML格式有更好的错误报告.
我看着nltk.这不是微不足道的,但我可以推荐自然语言工具包文档,CH 7 - 从文本中提取信息,特别是7.5 Named Entity Recognition.在本节的最后,他们指出:
NLTK提供了一个已经过训练以识别命名实体的分类器,可以使用函数nltk.ne_chunk()访问.如果我们设置参数binary = True,那么命名实体只被标记为NE; 否则,分类器会添加类别标签,例如PERSON,ORGANIZATION和GPE.
您正在指定True,但您可能需要类别标签,因此:
chunked_sentences = nltk.batch_ne_chunk(tagged_sentences)
Run Code Online (Sandbox Code Playgroud)
这提供了类别标签(命名实体类型),这看起来很有希望.但是在对你的文本和一些带位置的简单短语进行尝试之后,显然需要更多的规则.阅读文档以获取更多信息.