我有一个文本数据帧,我想要替换一些子字符串的文本。例如:
"[' Foods are adequately protected from\\n contamination during handling and storage.', ' Food handler hygiene and hand washing is\\n properly followed.', ' Foods are cooked, cooled and stored at\\n proper temperatures.', ' Garbage and/or waste is properly stored\\n and removed.', ' Pest control practices are properly maintained.', ' Equipment and utensils are properly cleaned,\\n sanitized and maintained.', ' Food premise is properly maintained in a clean\\n and sanitary condition.']"
我要将'\n‘替换为'’。
[sub.replace('\\n', '') for sub in abc_test]
其中abc_test只是数据帧内容的第一行。当我应用此函数时,结果与我所希望的结果不同。
['[',
"'",
' ',
'F',
'o',
'o',
'd',
's',
' ',
'a',
'r',
'e',
'
任何帮助都将不胜感激。
发布于 2020-10-06 16:51:22
这里的要点是,您的字符串包含反斜杠和n
字符的组合,而不是换行符。因此,"\n"
( LF换行符,字符)和"\\n"
(与换行符LF匹配的\n
正则表达式转义)都不起作用。
您可以使用
df['res'] = df['text'].str.replace(r"\\n", "")
Pandas测试:
>>> import pandas as pd
>>> df = pd.DataFrame({'text': [' Foods are adequately protected from\\n contamination during handling and storage.', ' Food handler hygiene and hand washing is\\n properly followed.', ' Foods are cooked, cooled and stored at\\n proper temperatures.', ' Garbage and/or waste is properly stored\\n and removed.', ' Pest control practices are properly maintained.', ' Equipment and utensils are properly cleaned,\\n sanitized and maintained.', ' Food premise is properly maintained in a clean\\n and sanitary condition.']})
>>> df['res'] = df['text'].str.replace(r"\\n", "")
>>> df
text res
0 Foods are adequately protected from\n contami... Foods are adequately protected from contamina...
1 Food handler hygiene and hand washing is\n pr... Food handler hygiene and hand washing is prop...
2 Foods are cooked, cooled and stored at\n prop... Foods are cooked, cooled and stored at proper...
3 Garbage and/or waste is properly stored\n and... Garbage and/or waste is properly stored and r...
4 Pest control practices are properly maintained. Pest control practices are properly maintained.
5 Equipment and utensils are properly cleaned,\... Equipment and utensils are properly cleaned, ...
6 Food premise is properly maintained in a clea... Food premise is properly maintained in a clea...
https://stackoverflow.com/questions/64228767
复制相似问题