strip and split 如何剥离列表

strip and split how to strip the list

我的代码:

readfile = open("{}".format(file), "r")

lines = readfile.read().lower().split()

elements = """,.:;|!@#$%^&*"\()`_+=[]{}<>?/~"""
for char in elements:
    lines = lines.replace(char, '')

这有效并删除了特殊字符。但我需要帮助去除“-”和“'”

例如,“saftey-dance”可以,但“-hi-”不行,但“我会”可以,但“'hi”不行

我只需要去掉开头和结尾

它不是一个字符串,它是一个列表。

我该怎么做?

也许你可以尝试 string.punctuationstrip:

import string

my_string_list = ["-hello-", "safety-dance", "'hi", "I'll", "-hello"]

result = [item.strip(string.punctuation) for item in my_string_list]
print(result)

结果:

['hello', 'safety-dance', 'hi', "I'll", 'hello']

首先,在循环中使用str.replace是低效的。由于字符串是不可变的,因此您将在每次迭代中创建一个需要的字符串。您可以使用 str.translate 一次删除不需要的字符。

关于仅在破折号不是边界字符时才删除破折号,这正是 str.strip 所做的。

您要删除的字符似乎也对应于 string.punctuation'-' 的特殊情况。

from string import punctuation

def remove_special_character(s):
    transltation = str.maketrans('', '', punctuation.replace('-', ''))
    return ' '.join([w.strip('-') for w in s.split()]).translate(transltation)

polluted_string = '-This $string contain%s ill-desired characters!'
clean_string = remove_special_character(polluted_string)

print(clean_string)

# prints: 'This string contains ill-desired characters'

如果你想将它应用到多行,你可以用列表理解来实现。

lines = [remove_special_character(line) for line in lines]

最后,要读取文件,您应该使用 with 语句。

with open(file, "r") as f
    lines = [remove_special_character(line) for line in f]