python - 如何在 Python 中使用 xlrd 从具有多个值的单个单元格中获取单独的值,以逗号分隔?
问题描述
因此,假设我在 excel 中有一个名为名称的列,然后在第一个单元格中它有“George,Bill,Sally”。我如何使用 xlrd 分离这些值并在 Python 中打印它们。
csv_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +
"\FilePath\\"
file_location = csv_dir + "filename"
wb = xlrd.open_workbook(file_location)
sheet = wb.sheet_by_index(0)
for row in range(1, sheet.nrows):
name = sheet.cell_value(row, 0)
print(name)
所以现在我得到乔治、比尔、莎莉作为结果。我希望它打印为:
George
Bill
Sally
每个名称一次打印一行。基本上我想打印出三个不同的字符串,每个字符串代表一个名称,而不是所有三个名称的一个字符串。
解决方案
如果您只想打印出来,请使用str.replace()
for row in range(1, sheet.nrows):
name = sheet.cell_value(row, 0)
print(name.replace(',', '\n').replace(' ', ''))
如果您想实际将值放入列表中,请使用str.split()
for row in range(1, sheet.nrows):
name = sheet.cell_value(row, 0)
as_list = name.replace(' ', '').split(',') # the replace is to remove any spaces
print(*as_list, sep='\n')
推荐阅读
- r - row.name 使用 `structure` 函数作为 c(NA, *integer*)
- javascript - 如何使用 TypeScript 为 IE11/Edge/Chrome/Firefox 编译 Web 组件?
- c++ - 带有vulkan的GLFW,如何摆脱内存泄漏?
- javascript - 在javascript中将null转换为空字符串
- ssis - 初始构建中的历史数据集
- r - Adding geom_text from different data frame to facets
- python - 如何在迭代之间建立时间缓冲
- c# - 在本地方法中返回列表(C#)
- python - 在脚本的所有数据帧上错误添加的变量 - Python 3
- javascript - 如何让我的 selenium-standalone 启动 - selenium-standalone start