多个.replace()??了解从excel文件(Python)添加到记录中的“u”

2024-10-04 11:26:59 发布

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

我需要一些代码帮助:

import pyexcel as pe
import pyexcel.ext.xls
import pyexcel.ext.xlsx

def randStrings(excelFile1,excelFile2):
    getNameList = pe.get_sheet(file_name=excelFile1)
    randName = sum([i for i in getNameList],[])
    getCompanyList = pe.get_sheet(file_name=excelFile2)
    randCompany = sum([i for i in getCompanyList],[])
    randStrings.name = random.choice(randName)
    randStrings.combinedString = random.choice(randName) + "@" + random.choice(randCompany).lower().replace(" ","").replace("'","").replace("/","").replace(".","").replace(",","") +".com"
    return randStrings.name, randStrings.combinedString

randStrings("names.xlsx","companys.xlsx")
data = {'user_name':randStrings.name,'user_email': randStrings.combinedString}
print data

我的输出是:{'user\u name':u'duky','user\u email':u'geri@belleladi.com'}

有两件事需要帮助或建议:

1.是否有人有想法或能解释为什么从excel表中获取记录时会有“u”字符??如何从输出中删除这个

  1. 我已经做了很长的.replace()来清除excel中的小精灵。有没有一个简短或更干净的方法来做到这一点?像Python一样。我还没有找到任何关于格式化的多个替换的例子

干杯


Tags: nameimportrandompyexcelxlsxextreplacepe
3条回答

你的代码还有一个其他答案没有解决的问题

您正在使用一种非常不寻常的技术从函数中“返回”数据。尽管您有一个return语句,但函数调用实际上并没有保存返回的对象,因此return语句是多余的

将数据作为函数属性randStrings.namerandStrings.combinedString附加到函数对象本身。当然,这是可行的,但正如我所说的,这是相当不寻常的,而且很少使用函数属性,当它们使用时,它是用来做一些特殊的事情,比如在函数调用之间保存值

从函数传回数据的正常方法如下:

def randStrings(excelFile1,excelFile2):
    getNameList = pe.get_sheet(file_name=excelFile1)
    randName = sum([i for i in getNameList],[])
    getCompanyList = pe.get_sheet(file_name=excelFile2)
    randCompany = sum([i for i in getCompanyList],[])
    name = random.choice(randName)
    combinedString = random.choice(randName) + "@" + random.choice(randCompany).lower().replace(" ","").replace("'","").replace("/","").replace(".","").replace(",","") +".com"
    return name, combinedString

name, combinedString = randStrings("names.xlsx","companys.xlsx")
data = {'user_name':name,'user_email': combinedString}

您的编码是Unicode,这不是Excel使用的本机编码。这就是为什么你在琴弦前得到“u”

您是否在Excel中尝试过以下操作:数据->;导入数据->;在导入向导中指定编码(可能是utf8)

记录前面的u'表示它们被编码为unicode

>>> a=u'test'
>>> a
u'test'
>>> type(a)
<type 'unicode'>
>>> b="b"
>>> b
'b'
>>> type(b)
<type 'str'>
>>> 

相关问题 更多 >