我有一个像这样的长字符串:
'[("He tended to be helpful, enthusiastic, and encouraging, even to studentsthat didn\'t have very much innate talent.\\n",), (\'Great instructor\\n\',), (\'He could always say something nice and was always helpful.\\n\',), (\'He knew what he was doing.\\n\',), (\'Likes art\\n\',), (\'He enjoys the classwork.\\n\',), (\'Good discussion of ideas\\n\',), (\'Open-minded\\n\',), (\'We learned stuff without having to take notes, we just applied it to what we were doing; made it an interesting and fun class.\\n\',), (\'Very kind, gave good insight on assignments\\n\',), (\' Really pushed me in what I can do; expanded how I thought about art, the materials used, and how it was visually.\\n\',)
我想立刻从这个字符串中删除所有[,(,",\,\ n \ n \ n。不知何故,我可以一个接一个地删除它,但总是以' \ n'有没有什么有效的方法可以删除或翻译所有这些字符或空行符号? 由于我的senectiecs不长,所以我不想使用像早期问题的字典方法。
答案 0 :(得分:0)
如果字符串是正确的python表达式,那么你可以使用ast模块中的literal_eval将字符串转换为元组,之后你可以处理每个元组。
from ast import literal_eval
' '.join(el[0].strip() for el in literal_eval(your_string))
如果没有,那么你可以使用它:
def get_part_string(your_string):
for part in re.findall(r'\((.+?)\)', your_string):
yield re.sub(r'[\"\'\\\\n]', '', part).strip(', ')
''.join(get_part_string(your_string))
答案 1 :(得分:0)
也许您可以使用正则表达式来查找要替换的所有字符
s = s.strip()
r = re.compile("\[|\(|\)|\]|\\|\"|'|,")
s = re.sub(r, '', s)
print s.replace("\\n", "")
我对“\ n”有一些问题,但在正则表达式之后也很容易删除。
答案 2 :(得分:-2)
一种解决方案是使用ASCII表值,基本上你只是遍历字符串然后如果字符串中的字符是符号之一[,(,",\,\ n,你将替换它:
# s is your string
for i in s:
if (ord(i) == 91)|(ord(i)==10):
s=s.replace(i,'')
ord(' [')= 91
ord(' \ n')= 10
这不是最好的方法,但它会完成这项工作。