python 讀取本地txt檔案的doc的url,自動下載,查詢內容
阿新 • • 發佈:2018-12-16
參考文章
python讀寫doc/docx/txt/xls檔案
python讀取word文件表格裡的資料
使用python找到指定路徑下的全部txt(可以是jpg,doc等等)檔案
獲取txt中儲存的url地址
import re
import urllib.request
# 讀取本地html中url地址(提前改下字尾)
with open(r"C:/Users/mfml1073278014/Desktop/1.txt",'r') as f:
# print(type(f.read()))
l= re.findall(r"http://jyu.good-edu.cn/editor_files/\S*.doc" , f.read()) # 正則,匹配裡面的url
count = 0
for url in l:
count += 1
print(url)
urllib.request.urlretrieve(url, str(count)+"_info.doc")
print(count)
下載儲存的url中的內容
import os
root = "E:/Django/DA/chapter01/docx"
# 遞迴遍歷,找到需要的檔名,儲存在ret中
def findfile(path, typ, ret):
filelist = os.listdir(path)
for filename in filelist:
de_path = os.path.join(path, filename)
if os.path.isfile(de_path):
if de_path.endswith(typ):
ret.append(de_path)
else:
findtxt(de_path, typ, ret)
ret = []
findfile(path=root, typ=".doc", ret= ret)
print(ret)
改變格式
from win32com import client as wc
# 轉換 doc to docx
def toDocx(path):
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(path) # 目標路徑下的doc檔案
extension = os.path.splitext(path)[1] # 獲得字尾
path = path.replace(extension, '.docx') #改字尾為docx
doc.SaveAs(path, 12, False, "", True, "", False, False, False, False) # 轉化後路徑下的檔案
doc.Close()
word.Quit()
for p in ret:
print(p)
toDocx(p) # 轉換為docx
os.remove(p) # 刪除原有的doc檔案
遍歷docx檔案,查詢關鍵字
import docx
final = set()
def find_info(target):
# 獲取文件物件
for word in ret:
file = docx.Document(word)
# 輸出每一段的內容
for para in file.paragraphs:
# print(para.text)
eight_date = re.findall(target, para.text, re.IGNORECASE)
if eight_date:
final.add(word)
try:
tables = file.tables # 獲取檔案中的表格集
table = tables[0] # 獲取檔案中的第一個表格
for i in range(1, len(table.rows)): # 從表格第二行開始迴圈讀取表格資料
result = table.cell(i, 0).text + "" + table.cell(i, 1).text + table.cell(i, 2).text + table.cell(i, 3).text
# cell(i,0)表示第(i+1)行第1列資料,以此類推
eight_date = re.findall(target, result, re.IGNORECASE)
if eight_date:
final.add(word)
except:
# print("IndexError: list index out of range")
pass
find_info("c\+\+")
for s in final:
print(s)