简体   繁体   English

从文本文件字符串中删除特定字符

[英]remove specific characters from text file string

I have a text file with the following line in it: ('larry', 3, 100) I need to assign the three parts of it to different variables using a method close to what I have below. 我有一个文本文件,其中包含以下行:('larry',3,100)我需要使用一种与下面类似的方法将其三个部分分配给不同的变量。 So far I can split it down, but I cannot remove the brackets and apostrophes from the result. 到目前为止,我可以将其拆分,但是无法从结果中删除括号和撇号 I have tried other solutions on stackover for hours to no avail... 我已经尝试了几个小时的stackover其他解决方案,但无济于事...

filecontent = filename.read().strip().split(',')

for i in filecontent:
    name = filecontent[0]
    weeks_worked = filecontent[1]
    weekly_payment = filecontent[2] 

print ("name:" + name)
print ("weeks worked:" + weeks_worked)
print ("weekly payment:" + weekly_payment)

gives the result: 给出结果:

name:('larry' 名称:('larry'

weeks worked:3 工作周数:3

weekly payment:100) 每周付款:100)

How do I make it show just: 我如何使其仅显示:

name:larry 名称:larry

weeks worked:3 工作周数:3

weekly payment:100 每周付款:100

You'll want to use ast.literal_eval here, which will convert the string to a tuple: 您将在此处使用ast.literal_eval ,它将字符串转换为元组:

import ast
filecontent = ast.literal_eval(filename.read().strip())

You also don't need a for-loop, you can also just do: 您也不需要for循环,也可以这样做:

name, weeks_worked, weekly_payment = filecontent

You can use regex either after or before split. 您可以在分割之后或之前使用正则表达式。

    filecontent = filename.read().strip().split(',')

    for i in filecontent:
        name = re.sub(r'\(|\)|\'','',filecontent[0])
        weeks_worked =  re.sub(r'\(|\)|\'','',filecontent[1])
        weekly_payment = re.sub(r'\(|\)|\'','',filecontent[1])

OR I would prefer doing this 或者我更喜欢这样做

   filecontent = re.sub(r'\(|\)|\'','',filename.read().strip()).split(',')

And then do your usual stuff. 然后做平常的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM