Skip to main content
 首页 » 编程设计

python之单独浏览一个列表

2025年05月04日12jpfss

除了一些 Ruby 之外,我的编码背景非常有限,所以如果有更好的方法,请告诉我!

本质上,我有一个充满文字的 .txt 文件。我想导入 .txt 文件并将其转换为列表。然后,我想获取列表中的第一项,将其分配给一个变量,并在发送出去的外部请求中使用该变量以获取单词的定义。返回定义,并将其放入不同的 .txt 文件中。完成后,我希望代码获取列表中的下一项并再次执行所有操作,直到列表耗尽。

下面是我正在编写的代码,可以让我了解我现在的位置。我仍在尝试弄清楚如何正确地遍历列表,而且我很难解释文档。

如果这已经被问到,请提前道歉!我进行了搜索,但找不到任何内容可以具体回答我的问题。

from __future__ import print_function 
import requests 
import urllib2, urllib 
from bs4 import BeautifulSoup 
 
lines = [] 
 
with open('words.txt') as f: 
    lines = f.readlines() 
 
for each in lines 
 
 
wordlist = open('test.txt', 'a') 
 
word = ##figure out how to get items from list and assign them here 
 
url = 'http://services.aonaware.com/DictService/Default.aspx?action=define&dict=wn&query=%s' % word 
 
# print url and make sure it's correct 
 
html = urllib.urlopen(url).read() 
# print html (deprecated) 
soup = BeautifulSoup(html) 
visible_text = soup.find('pre')(text=True)[0] 
 
print(visible_text, file=wordlist) 

请您参考如下方法:

让一切都在循环中。像那样:

with open('test.txt', 'a') as wordlist: 
    for word in lines: 
        url = 'http://services.aonaware.com/DictService/Default.aspx?action=define&dict=wn&query=%s' % word 
        print url 
        # print url and make sure it's correct 
        html = urllib.urlopen(url).read() 
        soup = BeautifulSoup(html) 
        visible_text = soup.find('pre')(text=True)[0] 
        wordlist.write("{0}\n".format(visible_text)) 

其次,一些建议:

  1. f.readlines() 不会丢弃结尾的 \n。所以,我会使用 f.read().splitlines()

    lines = f.read().splitlines() 
    
  2. 您不要使用 [ ] 初始化 lines 列表,因为您一次性形成列表并将其分配给 lines 。仅当您考虑对列表使用 append() 时,才需要初始化列表。因此,不需要以下行。

    lines = [] 
    
  3. 您可以通过以下方式处理KeyError:

    try: 
        value = soup.find('pre', text=True)[0] 
        return value 
    except KeyError: 
        return None