我還是一個初學者,但我覺得這似乎很簡單。它更多地是您開始構建和定製的起點。我只選擇做一列(Person),我很確定你在這個例子中需要做的所有事情。你必須通過運行在未來2個命令來安裝需要訪問電子表格中的2個需要Python庫(假設你使用某種類型的Linux,你沒有提供足夠的信息):
PIP安裝xlrd
PIP安裝xlutils
這裏的例子中,評論大致解釋每行做什麼。
#!/usr/bin/env python
''' Required to install these libraries to access spreadsheets
pip install xlrd
pip install xlutils
'''
import os, re, string
from xlutils.copy import copy
from xlrd import open_workbook
book_ro = open_workbook("spreadsheet.xls")
# creates a writeable copy
book = copy(book_ro)
# Select first sheet
sheet1 = book.get_sheet(0)
# Create list to hold people, otherwise we have to figure out the next empty column in spreadsheet
peopleList = []
# Get list of files in current folder and filter only the txt files
for root, dirs, docs in os.walk('.', topdown=True):
for filename in docs:
if (filename.endswith(".txt")) or (filename.endswith(".TXT")):
filepath=(os.path.join(root, name))
# Open file read only
TxtFile = open(filepath,"r")
# Read all the lines at once in variable
lines = TxtFile.readlines()
# Finished reading, close file
TxtFile.close()
# Convert file to big string so it can be searched with re.findall
lines = '\n'.join(lines)
# Find all occurences of "person:" and capture rest of line
people = re.findall(r'person: (.*)',lines)
# Remove delimeters/special character separating each name
people = map(lambda x: x.strip(), people)
# If file has more than 1 person, add each one individually
for person in people:
peopleList.append(person)
row = 0
column = 0
# Sort the list and remove duplicates (set(sort)), then step thru list and write to spreadsheet
for person in set(sorted(peopleList)):
sheet1.write(row, column, person)
row += 1
# This will overwrite the original spreadsheet if one existed
book.save("spreadsheet.xls")
歡迎來到SO:請參加[導覽]並閱讀[MCVE]。你的問題對於這個論壇來說太廣泛了,你可能無法得到你需要的所有答案。你總是可以聘請一些幫助。我會寫你的代碼爲$ 5和一些啤酒:) –