【问题标题】:Remove specific characters from String List - Python [duplicate]从字符串列表中删除特定字符 - Python [重复]
【发布时间】:2017-11-02 20:53:11
【问题描述】:

我有一个文件,我从中读取了一组单词,这个文件是“file1.txt”。

“file1.txt”文件示例内容如下:

Hello how are you? Very good!

我必须做的是消除示例中出现的那些符号字符。

对于前面的示例,最后的短语如下:

Hello how are you Very good

我的想法是,读完所有单词后,将它们存储在一个列表中,以应用相应的“替换”来删除所有类型的无效字符。

我想到的另一个想法是,当我加载 .txt 文件时直接在此处应用替换,但是在尝试了不同的方法后,我不应用删除无效字符。

这是我的代码:

# -*- coding: utf-8 -*-

import sys 


def main():

  characters = '!?¿-.:;'
  aux = []

  with open('file1.txt','r') as f:
    for line in f:
      for word in line.split():
        aux.append(word)

  for a in aux:
    for character in characters:
      a = a.replace(character,"")

if __name__ == '__main__':
    main()

如您所见,我的代码的第一部分将 txt 文件中的所有单词存储在一个名为“aux”的列表中。

但我不知道如何应用“替换”方法来消除我的话中的无效字符。

【问题讨论】:

  • 你必须直接在 aux[xxx] 上工作,或者使用列表理解重建它。

标签: python replace


【解决方案1】:

通过直接遍历文件并将其内容写入变量并过滤掉不需要的字符,可以更简单地实现它。

例如,这里是'file1.txt' 文件,其内容为:

Hello how are you? Very good!

那么我们可以这样做:

def main():

    characters = '!?¿-.:;'

    with open('file1.txt') as f:
        aux = ''.join(c for c in f.read() if c not in characters)

    # print(aux) # Hello how are you Very good

正如我们所见,aux 是文件的内容,没有不需要的字符,可以根据所需的输出格式轻松编辑。

例如,如果我们想要一个单词列表,我们可以这样做:

def main():

    characters = '!?¿-.:;'

    with open('file1.txt') as f:
        aux = ''.join(c for c in f.read() if c not in characters)
        aux = aux.split()

    # print(aux) # ['Hello', 'how', 'are', 'you', 'Very', 'good']

【讨论】:

  • 是的更简单,但我不知道为什么你的想法的解决方案给了我,所有的单词都由元音分隔,例如它给我的“你好”这个词“h”“ e" "l" "l" "o"
  • @fiticida, aux 这里只是一个文件的内容,没有不需要的字符。它可以根据您想要的输出类型轻松编辑。
  • @fiticida,例如,如果你想要单词列表,只需添加aux = aux.split()
  • 喜欢吗? aux = aux.split().join(c for c in f.read() if c not in characters)。抱歉,我是 python 新手,列表暂时想念我
  • @fiticida,检查最后的编辑。您也可以在 1 行中实现 split(),但在这种情况下,split() 应该在末尾:aux = ''.join(c for c in f.read() if c not in characters).split()
【解决方案2】:

您只是重新分配循环变量,而不是改变列表!将最后一个循环更改为:

for i in range(len(aux)):
  for character in characters:
    # this actually changes the list element
    aux[i] = aux[i].replace(character, "")  

你的旧版本大致相当于:

for i in range(len(aux)):
  a = aux[i]
  for character in characters:
    a = a.replace(character, "") 
    # aux[i] is unimpressed ;)

【讨论】:

  • 天哪,完全正确,谢谢
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 2017-06-18
  • 2014-08-02
  • 2012-10-21
  • 2014-05-14
  • 2021-05-08
  • 2020-06-02
  • 2011-04-25
相关资源
最近更新 更多