包含多个字符串的列表到excel fi

2024-04-19 08:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个反应列表,我们称之为

A=['ABC+B->;C+D','EGF(+)+F+G->;I+J+K','2000~XLM+Y->;2~Q']

我想写一个excel文件,每个反应物和产物都在不同的单元格里,前面有化学计量常数。例如

enter image description here

首先,我需要用分隔符来分隔字符串,比如-->;和+,如果前面没有数字,如何在反应物前面加1?用熊猫或xlwt写作更好吗?你知道吗

谢谢你的帮助!你知道吗

import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test')
new_list= []
for j in reaction:
   j = j.split ('--->')
   new_list.append(j)  
for j in new_list:
    for i in range(1, 180):
        ws.write(i,0, j[0:i]) 
        ws.write(i,1, j[i:2])

我知道这很难,因为在一个元素中有(+)是不能分开的。我想也许把每件事都转换成它自己的字符串,然后找到我们想要的分隔符并把它们分开?我再次编辑了代码,它给了我我想要的东西,但它说,它覆盖了同一个单元格,我不知道为什么,导致迭代通过1,180和从列表中的字符串???如果我让这个循环正常工作,我就可以在excel中手动编辑代码了。你知道吗


Tags: 字符串ingt编辑列表newforws
1条回答
网友
1楼 · 发布于 2024-04-19 08:08:09

编辑我的答案…希望这有帮助

import re
import xlwt

def write_data(row,col,data,sheet):
    #groups = data.split('+')
    groups = re.split(r"\+(?!\))",data) #split on '+', but dont split if the + is followed by a ')' like in (+)
    for g in groups:
        digits_match = re.match(r'[0-9]+',g)
        if digits_match is None: #doesnt start with a digit
            digit = 1
            index = 0
        else:
            digit = digits_match.group() #take all digits
            index = len(digit)
        sheet.write(row,col,int(digit))
        col+=1
        sheet.write(row,col,g[index:])
        col+=1
    return col

book = xlwt.Workbook()
sheet = book.add_sheet('reactions')
row = 0
A = ['A+B ->4C+D', 'E(+)+F+3G ->I+J+KLM', 'X+Y ->2~Q', 'ABC+B ->C+D', '4EGF(+)+F+G ->I+J+K', '2000~XLM+Y ->2~Q']
for reaction in A:
    reaction = reaction.replace('~','') # assuming u dont need this character
    #add any other chars here if reqd...#
    col = 0
    splits = reaction.split(' ->')
    col = write_data(row,col,splits[0],sheet)
    sheet.write(row,col,' ->')
    col += 1
    col = write_data(row,col,splits[1],sheet)
    row += 1
book.save('temp1.xls')

相关问题 更多 >