如何将远程单词列表存储到个人文件中?

时间:2017-03-21 18:31:51

标签: python

以下是我收到的错误消息:

Traceback (most recent call last):
  File "datalister.py", line 10, in <module>
    wordlist.write(words)
TypeError: expected a string or other character buffer object

我的代码:

import random, sys
from urllib import urlopen
word_url = "http://scrapmaker.com/data/wordlists/dictionaries/rockyou.txt"
words = []

for word in urlopen(word_url).readlines():
    print "Doing it now..."
    wordlist = open('wordlist.txt', 'w')
    wordlist.write(words)
    wordlist.close()
    print "File written successfully!"

2 个答案:

答案 0 :(得分:1)

错误正是它所说的:你必须给一个字符串,而不是列表。你关闭了一封信:你需要写单词,而不是单词。这个简单的改变修复了程序......我想。它很适合我。

wordlist = open('wordlist.txt', 'w')
for word in urlopen(word_url):
    print "Doing it now..."
    wordlist.write(word)
    print "File written successfully!"
wordlist.close()

由于每行一个单词,在开始写东西之前,你真的不需要读完整个文件;只需使用默认生成器就可以根据需要获取行。

另外,请注意,您从未在列表中添加任何内容单词。如果您想要的只是单词列表,您也可以删除该变量。

答案 1 :(得分:0)

这是我开始尝试的代码:

import random, sys
from urllib import urlopen
word_url = "http://scrapmaker.com/data/wordlists/dictionaries/rockyou.txt"
wordlist = open('wordlist.txt', 'w')
for word in urlopen(word_url):
    print "Added: ", word
    wordlist.write(word)

print "Successfully written all words to file!"
wordlist.close()