[好吧,我认为我只是缺少连接器,对于python来说还很新。
目标:读取CSV读取目录中的所有文件名如果索引(x)处的ROW =目录中的文件名,则打开HTML文件,然后用HTML文件中的文本替换index(x)处的文本]
到目前为止的代码:
import fileinput
import csv
import os
import sys
import glob
from bs4 import BeautifulSoup
htmlfiles_path = "c:\\somedirectory\\" #path to directory containing the html files
filename_search = glob.glob("c:\\somedirectory\\*.HTM") #get list of filenames
#open csv
with open ('content.csv', mode='rt') as content_file:
reader = csv.reader (content_file, delimiter=',')
for row in reader:
for field in row:
if filename_search(some matching logic i am stuck on):
for htmlcontentfile in glob.glob(os.path.join(path, ".HTM")):
markup(htmlcontentfile)
soup = BeatifulSoup(open(markup, "r").read())
content_file.write(soup.get_text())
#i think something else goes here
我让csv阅读器可以工作,并且可以通过glob提取文件名列表,但在连接这些文件时遇到了一些麻烦。任何帮助都将是极好的。
我查询了其他问题,其中一些代码基于此,但是我在python中没有找到任何针对此挑战的内容。如果有,请指示我正确的方向!
EDIT1:在我的代码中,我在csv中使用“ wt”。但这不是卡住的地方。
我有一个充满文件的文件夹。例如:
content / d100.htm内容/d101q.htmcontent / d102s.htm
以及CSV:范例CSVCSV档案:
标题名称位置加州总统d100.html
目标:打开csv,在“位置”下查找“目录”文件夹中任何文件的匹配项如果找到匹配项,则打开相应的HTM文件,仅解析文本用文件的文本内容替换csv中的字段
这有意义吗?
答案:
1)@barny如果我没有运行代码,我不会在这里发布。我为误解我的要求深表歉意。
无论如何,我通过根据问题陈述进行了一些更改,并使用Excel来完成它,从而弄清楚了。
原始询问:
CSV与]>
文字|回答|目标文件内容
一些文字|请参考文件001.htm |其他一些文字|请参考文件002.htm |
查找文件,并将内容解析到它旁边的列。
稍有改变的问:
将所有htm文件解析为一个csv,并列出它们各自的文件名。然后使用Excel匹配内容。
而不是让BSoup或Python进行匹配,Excel已经具有一个函数index(match())来完成请求的第二部分。因此,我让Python和Bsoup打开了每个HTML文件,并将其放在CSV中。我还在另一列中输入了很长的文件名。像这样:
文件:content / 001.htm
content / 002.htm
content / 003.htm
CSV输出的预期格式:
HTML文件的内容|文件名
代码:
import fileinput import csv import os import sys import glob from bs4 import BeautifulSoup path = "<the path>" def main(): for filepath in glob.glob(os.path.join('<the path>', '*.HTM')): #find folder containing html files with open(filepath) as f: contentstuff = f.read() #find an html file, and read it soup = BeautifulSoup(contentstuff, "html.parser") #parse the html out with open (path + '\\htmlpages.csv', 'a', encoding='utf-8', newline='') as content_file: writer = csv.writer (content_file, delimiter=',') #start writer for file content to CSV fp = filepath[-12:] #trim the file name to necessary name for body_tag in soup.find_all('body'): bodye = (body_tag.text.replace("\t", "").replace("\n", "")) #deal with necessary formatting between Bsoup and Excel print(bodye) #show me the work writer.writerow([bodye, fp]) #do the actual writing
在将内容放入CSV后,我使用了一个index(match())来配对核心文件和新CSV中的文件名。