“将文本文件导入python”列表中的每个项目中都有\n个。如何在导入期间从每个项目中删除\n?

2024-05-17 00:16:32 发布

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

我使用以下代码将.txt文件中的文本提取到列表中

with open("german.txt", "r") as f:
    stopwords = []
    for item in f:
      # print(item)
      stopwords.append(item)
    print(stopwords) 

german.txt文件的示例

aber
alle
allem
allen
aller
alles
als

结果

['aber\n', 'alle\n', 'allem\n', 'allen\n'......

为什么每个项目都会有\n问题?有没有一种简单的方法可以在没有


Tags: 文件代码文本txt列表withopenitem
1条回答
网友
1楼 · 发布于 2024-05-17 00:16:32

您可以使用:

stopwords.append(item.rstrip())

{a1}方法:

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

相关问题 更多 >