我是一个noobie,我一直在努力研究这个简单的代码,所以我想我会寻求帮助。
我正在尝试打开CSV并解码网址文字,例如example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0
然后保存文件。我可以使用字符串轻松完成此操作,但我很难用CSV中的行来完成。
我到目前为止的尝试:
#reading
file1 = open('example.csv', 'r')
reader = csv.reader(file1)
url = []
for rows in reader:
url.append = urllib.unquote(rows).decode('utf8')
#also tried "url.append(urllib.unquote(rows).decode('utf8'))", but same error
file1.close()
#writing
file2 = open('example.csv', 'w')
writer = csv.writer(file2)
writer.writerows(url)
file2.close()
编辑:我收到的错误..
AttributeError: 'list' object has no attribute 'split'
你的方法有一些错误。
csv
模块没有任何好处,Python可以很好地读取文本文件。实际上,当您打开文本文件进行阅读时,“逐行”默认模式。open()
时声明文本文件所在的编码。 Python没有魔术文本编码检测器,当你没有指定编码时,正确读取文件可能在你的机器上运行而在另一台机器上运行,因为不同的计算机配置可能有不同的“默认”编码。ParseResult
对象,该对象可以方便地将URL的所有不同部分公开为属性。dict
。.append
是一个功能。你不能分配给它(.append = '...'
),你需要调用它(.append('...')
)。with
块更容易处理文件,因为with
会自动关闭文件。相比:
from urllib.parse import urlparse, parse_qs
with open('example.txt', 'r', encoding='utf-8') as file1:
titles = []
for url in file1:
parts = urlparse(url)
# -> ParseResult(
# scheme='http', netloc='example.com', path='', params='',
# query='title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0',
# fragment='')
q = parse_qs(parts.query)
# -> {'title': ['правовая защита']}
if 'title' in q:
titles.append(q['title'][0])
with open('titles.txt', 'w', encoding='utf-8') as file2:
file2.writelines(titles)
使用list comprehensions并删除不必要的注释,我们可以压缩上面的代码:
from urllib.parse import urlparse, parse_qs
with open('example.txt', 'r', encoding='utf-8') as file1:
queries = [parse_qs(urlparse(url).query) for url in file1]
with open('titles.txt', 'w', encoding='utf-8') as file2:
titles = [q['title'][0] for q in queries if 'title' in q]
file2.writelines(titles)
对我而言,您可能会从阅读器中获取单独的行。我猜这些可能是通过索引提供的。
for row in reader
url.append = urllib.unquote(row[0]).decode('utf8')
如果列表抽象还不够,还有一个DictReader。