gpt4 book ai didi

python - 在pandas python中删除文本中的 '\n'

转载 作者:行者123 更新时间:2023-12-03 17:31:58 25 4
gpt4 key购买 nike

以下代码是我用来删除 ['text'] 列中的\n 的当前代码:

df = pd.read_csv('file1.csv')

df['text'].replace('\s+', ' ', regex=True, inplace=True) # remove extra whitespace
df['text'].replace('\n',' ', regex=True) # remove \n in text

header = ["text", "word_length", "author"]

df_out = df.to_csv('sn_file1.csv', columns = header, sep=',', encoding='utf-8')

我也从建议中尝试过:
df['text'].replace('\n', '')
df['text'] = df['text'].str.replace('\n', '').str.replace('\s+', ' ').str.strip()

Output: ' What a smartass! \nLike he knows anything about real estate deals too...'



删除空格的代码正在运行。但不是在删除\n。任何人都可以帮助我解决这个问题吗?谢谢。

我也尝试根据此链接的建议解决 removing newlines from messy strings in pandas dataframe cells?但它仍然无法正常工作。

解决了:
df['text'].replace(r'\s+|\\n', ' ', regex=True, inplace=True) 

最佳答案

考虑到想要将更改应用于“文本”列,请选择该列作为

df['text']
然后,为了实现这一点,可以使用 pandas.DataFrame.replace
这让我们可以传递正则表达式 regex=True ,它将两个列表中的两个字符串都解释为正则表达式(而不是直接匹配它们)。
拿起 @Wiktor Stribiżew suggestion ,以下将完成工作
df['text'] = df['text'].replace(r'\s+|\\n', ' ', regex=True) 
This 正则表达式语法引用可能会有所帮助。

关于python - 在pandas python中删除文本中的 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com