【问题标题】:How to get a list of strings to print out vertically in a text file?如何获取要在文本文件中垂直打印的字符串列表?
【发布时间】:2016-03-31 14:01:01
【问题描述】:

我有一些从网站上提取的数据。这是我用来抓取它的代码(我的实际代码要长得多,但我认为这可以总结一下)。

lid_restrict_save = []
for t in range(10000,10020): 

    address = 'http://www.tspc.oregon.gov/lookup_application/' + lines2[t]

    page = requests.get(address)

    tree = html.fromstring(page.text)

    #District Restriction
    dist_restrict = tree.xpath('//tr[11]//text()')
    if u"District Restriction" in dist_restrict:
        lid_restrict_save.append(id2)

我正在尝试导出此列表:

print lid_restrict_save
[['5656966VP65', '5656966RR68', '56569659965', '56569658964']]

到一个文本文件。

f = open('dis_restrict_no_uniqDOB2.txt', 'r+')

for j in range(0,len(lid_restrict_save)):
    s = ( (unicode(lid_restrict_save[j]).encode('utf-8') + ' \n' ))
    f.write(s) 

f.close()

我希望文本看起来像这样:

5656966VP65
5656966RR68
56569659965
56569658964

此代码有效,但仅当我从 0 开始 range 时。

f = open('dis_restrict.txt', 'r+')

for j in range(0,len(ldob_restrict)):
    f.write( ldob_restrict[j].encode("utf-8") + ' \n' )

f.close()

当我尝试更改代码时,我不断收到此错误:

"AttributeError: 'list' object has no attribute 'encode'."

我尝试了hereherehere 的建议,但无济于事。

如果有人有任何提示,将不胜感激。

【问题讨论】:

  • lid_restrict_save 是一个嵌套列表。使用lid_restrict_save = lid_restrict_save[0]
  • @Farhan.K 我收到了IndexError: list index out of range。应该嵌套在循环内还是 lid_restrict_save = [] 之下?

标签: python-2.7 encoding utf-8


【解决方案1】:

lid_restrict_save 是一个嵌套列表,因此您不能对第一个元素进行编码,因为它不是字符串。

您可以使用以下命令写入 txt 文件:

lid_restrict_save = [['5656966VP65', '5656966RR68', '56569659965', '56569658964']]

lid_restrict_save = lid_restrict_save[0] # remove the outer list

with open('dis_restrict.txt', 'r+') as f:
    for i in lid_restrict_save:
        f.write(str(i) + '\n')

【讨论】:

  • 这有点不相关。我正在将一系列元素(姓名、雇主等)导出到 csv,它们是一个嵌套列表。我使用了lname = lname[0],外部括号消失了,但只打印了一项。你知道如何让括号消失但也可以通过range 10000-10020 打印吗?
  • 您需要将lname = lname[0] 放在循环之前。我的猜测是您将其放入循环中?
  • 我把它放在循环之后。当我把它放在循环之前我得到IndexError: list index out of range
  • 这听起来像是另一个问题。很抱歉,如果没有看到您的代码,我无法真正帮助您。
  • 这不是什么大问题。我只是好奇类似的编码是否可行。不过感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 2019-11-14
  • 1970-01-01
  • 2013-12-23
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多