【问题标题】:Downloading Data From .txt file containing URLs with Python again再次使用 Python 从包含 URL 的 .txt 文件下载数据
【发布时间】:2017-02-23 13:12:56
【问题描述】:

我目前正在尝试从 10 个 url 的 .txt 文件中提取原始数据,并将每一行(URL)的原始数据放入 .txt 文件中。然后使用 Python 对处理后的数据(去除 html 的同一原始 .txt 文件中的原始数据)重复该过程。

import commands
import os
import json

# RAW DATA
input = open('uri.txt', 'r')
t_1 = open('command', 'w')
counter_1 = 0

for line in input:
    counter_1 += 1
if counter_1 < 11:
    filename = str(counter_1)
    print str(line)
filename= str(count)
command ='curl ' + '"' + str(line).rstrip('\n') + '"'+ '> ./rawData/' + filename

output_1 = commands.getoutput(command)
input.close()

# PROCESSED DATA
counter_2 = 0
input = open('uri.txt','r')
t_2 = open('command','w')
for line in input:
    counter_2 += 1
    if counter_2 <11:
      filename = str(counter_2) + '-processed'
      command = 'lynx -dump -force_html ' + '"'+ str(line).rstrip('\n') + '"'+'> ./processedData/' + filename
    print command
output_2 = commands.getoutput(command)
input.close()

我正在尝试用一个脚本来完成所有这些工作。谁能帮我完善我的代码以便我可以运行它?对于 .txt 文件中的每一行,它应该完全循环一次代码。例如,我的 .txt 文件中的每个 url 行都应该有 1 个原始和 1 个已处理的 .txt 文件。

【问题讨论】:

    标签: python curl pycharm dump lynx


    【解决方案1】:

    将您的代码分解为函数。目前代码很难阅读和调试。创建一个名为get_raw() 的函数和一个名为get_processed() 的函数。然后对于你的主循环,你可以做

    for line in file:
        get_raw(line)
        get_processed(line)
    

    或类似的东西。此外,您应该避免使用像counter&lt;11 这样的“幻数”。为什么是11?它是文件中的行数吗?如果是,您可以使用len() 获取行数。

    【讨论】:

    • 文件有10行。我在想它会从 1、2、...10 开始计数。我的意思是放 10 个。
    • 我的意思是,如果您对值进行硬编码,那么您将永远无法处理具有不同行数的文件。您应该看到有多少行并将其用作迭代次数。
    • 我只需要对一份我知道其中有多少行的文档执行一次。我知道你来自哪里。
    猜你喜欢
    • 1970-01-01
    • 2017-03-23
    • 2016-10-24
    • 1970-01-01
    • 2021-07-02
    • 2021-11-21
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    相关资源
    最近更新 更多