【问题标题】:strip and split how to strip the list剥离和拆分如何剥离列表
【发布时间】:2018-05-28 21:50:26
【问题描述】:

我的代码:

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

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

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

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

所以例如“saftey-dance”可以但不是“-hi-”但“我会”可以但不是“'hi”

我只需要去掉开头和结尾

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

我该怎么做?

【问题讨论】:

标签: python python-3.x split strip


【解决方案1】:

也许你可以试试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']

【讨论】:

    【解决方案2】:

    首先,在循环中使用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]
    

    【讨论】:

    • @guide 我还添加了关于如何使用 with 语句安全打开文件的建议,我建议您阅读它。
    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多