从String List - Python中删除特定字符

时间:2017-11-02 20:53:12

标签: python replace

我有一个文件,我从中读取了一组单词,这个文件是" 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()

正如您所看到的,我的代码的第一部分存储在名为' aux'的列表中。来自txt文件的所有单词。

但我不知道如何申请"替换"从我的话中消除无效字符的方法。

2 个答案:

答案 0 :(得分:1)

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

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 ;)

答案 1 :(得分: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']
相关问题