代码之家  ›  专栏  ›  技术社区  ›  DwightD

Python 3.x版function:Converting string 列出并打印排除某些字符的输出

  •  -1
  • DwightD  · 技术社区  · 6 年前

    我在尝试将字符串转换为列表并生成所需的输出时遇到了一个问题。到目前为止,我有以下代码:

    def func():
    
        characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
        new_lst = []
        user = input("String: ")
        for i in user:
            if (i not in characters):
                #new_lst = user.split(' ')
                new_lst += i # I know this is the problem but I just don't know where to go from here
    
        print(new_lst)
    

    例如:

    Keep. hyphen- and apostrophe's only.
    

    电流输出:

    'K', 'e', 'e', 'p', ' ', 'h', 'y', 'p', 'h', 'e', 'n', '-', ' ', 'a', 'n', 'd', ' ', 'a', 'p', 'o', 's', 't', 'r', 'o', 'p', 'h', 'e', "'", 's', ' ', 'o', 'n', 'l', 'y']
    

    期望输出:

    ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
    

    谢谢你的帮助!

    3 回复  |  直到 6 年前
        1
  •  1
  •   xnx    6 年前

    首先将句子拆分为单词,然后迭代单词以重建(在内部循环中)修改的单词和(在外部循环中)单词列表:

    def func():
    
        characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
        new_lst = []
        user = input("String: ")
        for word in user.split():
            x = ''
            for i in word:
                if (i not in characters):
                    x += i # I know this is the problem but I just don't know where to go from here
            new_lst.append(x)
    
        print(new_lst)
    
    func()
    

    ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
    

    这不一定是一个代码审查网站,但我肯定会考虑更有效地命名变量,并对内部循环使用列表理解:

    def get_stripped_word_list(s):
        """Return a list of words in string s, excluding certain characters."""
    
        # Sequence of characters to strip, keeping ' and -
        characters = '?/><,.:;"[]{}=+()*&^%$#@!'
        words = s.split()
        modified_words = []
        for word in words:
            modified_word_letters = [c for c in word if c not in characters]
            modified_words.append(''.join(modified_word_letters))
        return modified_words
    
    s = input("String: ")
    print(get_stripped_word_list(s))
    
        2
  •  1
  •   vishalk    6 年前

    可以替换字符,也可以拆分字符

    def func():
    
        characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
        user = raw_input("String: ")
        for i in characters:
            user=user.replace(i,"")
        new_lst=user.split(" ")
        new_lst = [i.strip('.') for i in new_lst]
        print(new_lst)
    func()
    

    输出

    ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
    
        3
  •  0
  •   Onyambu    6 年前

    你可以用 sub re 模块:

    import re
    string = "Keep. hyphen- and apostrophe's only."
    
    re.sub("[^\w '-]", '', string).split()
    
    Out[672]: ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']