如何将元素末尾的分号从文本文件中删除到列表中

2024-09-29 23:17:02 发布

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

如何从文本文件中删除此分号(;)。我的文本文件的内容:

    201911007,1,28;
    201203008,1,28;
    199710014,1,28;
    201612010,1,28;
    201710017,1,28;

然后python读取它,如果我运行代码,它总是在28的末尾有分号

    with open("empMR.txt", 'r') as files:
    for dln in files:
        dln = dln.strip()
        if len(dln) >= 1:
            lii = dln.split(",")
            MR_empno.append(lii[0].strip())
            month.append(lii[1].strip())
            days_work.append(lii[2].strip())
print(days_work)

输出:['28;'、'28;'、'28;'、'28;'、'28;'、'28;']我想删除每个输出上的分号(;) 预期产出[28,28,28,28,28]


Tags: 代码txt内容withfilesopendayswork
3条回答

只需包含要删除的字符(包括;)

for dln in files:
    dln = dln.strip("; \n\r\t")

您不需要向其他函数添加额外的调用,尤其是不需要正则表达式(使用正则表达式可能还有其他正当理由,请参见下面的示例)

data = re.findall("([^,]*)\s*,\s*([^,]*)\s*,\s*([^;]*)\s*;",files.read())
for empNo,monthNo,days_work in data:
    print("E:",empNo, "Month:",monthNo, "Days Worked:",days_work)

有几种方法可以解决这个问题

  • 看看.replace()方法,类似dln.replace(';', '')的方法可能会有所帮助
  • 如果所有行看起来都一样,可以删除最后一个字符-dln = dln[:-1]可能会有帮助

您选择哪种方法取决于您对数据看起来总是一样的信心,以及您对哪种方法更满意

正则表达式是处理字符串的强大工具

import re
in_list = ['28;', '28;', '28;', '28;', '28;']
out_list = [re.sub(';', '', item) for item in in_list]
print(out_list)
['28', '28', '28', '28', '28']

相关问题 更多 >

    热门问题