Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将一系列字符串(加上一个数字)写入csv行_Python_Csv_Pandas - Fatal编程技术网

Python 将一系列字符串(加上一个数字)写入csv行

Python 将一系列字符串(加上一个数字)写入csv行,python,csv,pandas,Python,Csv,Pandas,这不是很好的代码,但我有一些代码可以从HTML文件中提取一系列字符串,并给我一系列字符串:作者,标题,日期,长度,文本。我有2000多个html文件,我想检查所有这些文件,并将这些数据写入一个csv文件。我知道所有这些最终都必须打包到for循环中,但在此之前,我很难理解如何从获取这些值到将它们写入csv文件。我的想法是先创建一个列表或元组,然后将其写入csv文件中的一行: the_file = "/Users/john/Code/tedtalks/test/transcript?language

这不是很好的代码,但我有一些代码可以从HTML文件中提取一系列字符串,并给我一系列字符串:
作者
标题
日期
长度
文本
。我有2000多个html文件,我想检查所有这些文件,并将这些数据写入一个csv文件。我知道所有这些最终都必须打包到
for
循环中,但在此之前,我很难理解如何从获取这些值到将它们写入csv文件。我的想法是先创建一个列表或元组,然后将其写入csv文件中的一行:

the_file = "/Users/john/Code/tedtalks/test/transcript?language=en.0"
holding = soup(open(the_file).read(), "lxml")
at = holding.find("title").text
author = at[0:at.find(':')]
title  = at[at.find(":")+1 : at.find("|") ]
date = re.sub('[^a-zA-Z0-9]',' ', holding.select_one("span.meta__val").text)
length_data = holding.find_all('data', {'class' : 'talk-transcript__para__time'})
(m, s) = ([x.get_text().strip("\n\r") 
      for x in length_data if re.search(r"(?s)\d{2}:\d{2}", 
                                        x.get_text().strip("\n\r"))][-1]).split(':')
length = int(m) * 60 + int(s)
firstpass = re.sub(r'\([^)]*\)', '', holding.find('div', class_ = 'talk-transcript__body').text)
text = re.sub('[^a-zA-Z\.\']',' ', firstpass)
data = ([author].join() + [title] + [date] + [length] + [text])
with open("./output.csv", "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for line in data:
            writer.writerow(line)
我一辈子都不知道如何让Python尊重这样一个事实:这些是字符串,应该存储为字符串,而不是字母列表。(上面的
.join()
正是我试图解决的问题。)


展望未来:以这种方式处理2000个文件是否更好/更有效,将它们剥离到我想要的内容,并一次写入一行CSV,还是在
pandas
中构建一个数据帧,然后将其写入CSV更好?(所有2000个文件=160MB,因此精简后,最终数据不能超过100MB,因此这里没有太大的大小,但前瞻性大小最终可能会成为一个问题。)

这将获取所有文件并将数据放入csv,您只需将包含html文件的文件夹的路径和输出文件的名称传递给:

import re
import csv
import os
from bs4 import BeautifulSoup
from glob import iglob


def parse(soup):
    # both title and author are can be parsed in separate tags.
    author = soup.select_one("h4.h12.talk-link__speaker").text
    title = soup.select_one("h4.h9.m5").text
    # just need to strip the text from the date string, no regex needed.
    date = soup.select_one("span.meta__val").text.strip()
    # we want the last time which is the talk-transcript__para__time previous to the footer.
    mn, sec = map(int, soup.select_one("footer.footer").find_previous("data", {
        "class": "talk-transcript__para__time"}).text.split(":"))
    length = (mn * 60 + sec)
    # to ignore time etc.. we can just pull from the actual text fragment and remove noise i.e (Applause).
    text = re.sub(r'\([^)]*\)',"", " ".join(d.text for d in soup.select("span.talk-transcript__fragment")))
    return author.strip(), title.strip(), date, length, re.sub('[^a-zA-Z\.\']', ' ', text)

def to_csv(patt, out):
    # open file to write to.
    with open(out, "w") as out:
        # create csv.writer.
        wr = csv.writer(out)
        # write our headers.
        wr.writerow(["author", "title", "date", "length", "text"])
        # get all our html files.
        for html in iglob(patt):
            with open(html, as f:
                # parse the file are write the data to a row.
                wr.writerow(parse(BeautifulSoup(f, "lxml")))

to_csv("./test/*.html","output.csv")

如果您只需要一个csv文件,那么首先创建一个数据帧,然后保存到一个csv文件不会比创建csv更快。你的代码中似乎有很多正则表达式,如果你能上传几个文件,我可以看一看,可能会使代码更容易理解,从而使编写更容易。另外,
writerow
需要一个iterable,因此您要传递的是一个数据列表
writerow([''.join(author)、title、data、length、text])
您真是太慷慨了,@padraickenningham。目前的工作在这里:。有一个
test
目录,里面有3个文件,我希望它能部分解释为什么我的regex/soup代码如此难看……不用担心,我看到了一些东西,我们可以简单地看一下,但我明天有空的时候会好好看一看。这真是太好了。昨晚当我回家时,我意识到是时候试穿一些“大男孩python裤子”并将其中的一些移动到一个函数中了,所以你们也给了我一个关于这样做的教程。有几个问题:首先,我想在剧本中把你归功于你。可以吗?你希望如何获得信任?其次,我看到您正在编码
作者
标题
明确性,这将在csv中生成一个
b'string'
。为什么会这样?再次感谢你。我不太清楚这里发生了什么。当我将它指向“big”目录时,它有完全相同的3个文件加上2000多个文件,它抛出一个错误
UnicodeDecodeError:“utf-8”编解码器无法解码位置3131的字节0x80:无效的开始字节
。我现在正在追查这件事…很有趣。将它指向
/test
,它就会工作。把它指向
/talks
,它没有。我不知道你在使用python3,你可以删除它。编码。我在所有文件上运行了代码,但我使用的是python2。我创建了第二个测试目录:这次是前十个文件。其中一个文件中必须包含奇数字符。如果我假设会有其他奇怪的字符。。。你对如何清洁它有什么建议吗?(我想我应该把这当作另一个问题提出。[?]