Python维基百科库

时间:2017-02-22 19:53:58

标签: python wikipedia-api

我使用python库Wikipedia来解析数据。当它到达代码的第二部分时,我遇到了页面错误。Page Errors

import wikipedia


print ("1: Searching Wikipedia for 'List of Lexus vehicles'")
try:
    print (wikipedia.page('List of Lexus'))
    print ('-' * 60)
except wikipedia.exceptions.DisambiguationError as e:
    print (str(e))
    print ('+' * 60)
    print ('DisambiguationError: The page name is ambiguous')
print


print ("2: Searching Wikipedia for 'List of Lexus (vehicles)'")
print (wikipedia.page('List of Lexus_(vehicles)'))
print


result = wikipedia.page('List of Lexus_(vehicles)').content.encode('UTF8')
print ("3: Result of searching Wikipedia for 'List of Lexus_(vehicles)':")
print (result)
print

lexus_count = result.count('ct','lfa','rx')
print


print ("The Wikipedia page for 'Lexus_(company)' has " + \
    "{} occurrences of the word 'Lexus'".format(lexus_count))
print

更新 我能够解析页面数据,但在计数时出现类型错误

23 print
24
25 lexus_count = result.count('ct','lfa','rx')
26 print
TypError: slice indices must be integers or None or have an __index__ method

2 个答案:

答案 0 :(得分:1)

您的计划存在多个问题。这是一个更新的程序,错误已修复并标记。

import wikipedia


print ("1: Searching Wikipedia for 'Lexus'")
try:
    print (wikipedia.page('Lexus'))
    print ('-' * 60)
except wikipedia.exceptions.DisambiguationError as e:
    print (str(e))
    print ('+' * 60)
    print ('DisambiguationError: The page name is ambiguous')
print


print ("2: Searching Wikipedia for 'Lexus (company)'")
result = wikipedia.page('Lexus (company)') 
# ERR; PAGE NAME SEPARATED BY SPACE NOT WITH AN UNDERSCORE
# <> PAGE ERROR AS PAGE WILL NOT BE FOUND.  
print (result)
print


result = result.content
print ("3: Result of searching Wikipedia for 'Lexus_(company)':")
print (result)
print

lexus_count = result.count('Lexus')
# changed variable name from orange_count -> lexus_count, as referenced in the print function below. 
# you were counting for 'lexus' you will not find any occurrences as this function is case sensitive.
print


print ("The Wikipedia page for 'Lexus_(company)' has " + \
    "{} occurrences of the word 'Lexus'".format(lexus_count))
print

希望这会有所帮助。

答案 1 :(得分:0)

您到底遇到了哪个页面错误?

根据维基百科文档:https://wikipedia.readthedocs.io/en/latest/quickstart.html#quickstart

  

但请注意 - 如果页面是消歧页面,wikipedia.summary将引发DisambiguationError,如果页面不存在,则会引发PageError(尽管默认情况下,它会尝试查找您建议和搜索的页面。 ):