简体   繁体   English

如何从列表中的字符串末尾去除特定标点符号并使所有单词小写

[英]How to strip specific punctuation from the end of strings in a list and make all words lower case

I have a list of strings and need certain punctuation stripped off the end of each string within the list.我有一个字符串列表,需要从列表中每个字符串的末尾删除某些标点符号。 The list is like:名单是这样的:

list = ['Twas', 'brillig,', 'and', 'the', 'slithy', 'toves', 'Did', 'gyre',
        'and', 'gimble', 'in', 'the', 'wabe:']  #the list is a lot longer

I need to strip off all punctuation that includes '"-,.:;?? only from the end of each string and make all words lower case.我只需要从每个字符串的末尾去掉所有包含'"-,.:;??标点符号,并将所有单词设为小写。

Io I need 'Twas' to become 'twas' and I need 'wabe:' to become 'wabe' , etc... other words in the list that i did not include here contain the other punctuation at the end. Io 我需要'Twas'变成'twas' ,我需要'wabe:'变成'wabe' ,等等……列表中我没有包含在此处的其他单词在末尾包含其他标点符号。

I tried using .rstrip() and .lower() case but I did not know how to use a for or while loop to go through each string in the list and do this.我尝试使用.rstrip().lower()大小写,但我不知道如何通过列表中的每个字符串使用 for 或 while 循环到 go 并执行此操作。 If there is another way that does not need to use .rstrip or .lower I am open to them.如果有另一种不需要使用.rstrip.lower的方法,我愿意接受。

I am a beginner with using python so the very basic answer would help me and if you could explain exactly what you do, it would be greatly appreciated.我是使用 python 的初学者,所以非常基本的答案会对我有所帮助,如果您能准确解释您的工作,我们将不胜感激。

>>> [el.lower().rstrip('\'\"-,.:;!?') for el in list]
['twas', 'brillig', 'and', 'the', 'slithy', 'toves', 'did', 'gyre', 'and', 'gimble', 'in', 'the', 'wabe']

This is a list comprehension, which is a one line way of writing a for loop which produces a list.这是一个列表理解,它是编写生成列表的 for 循环的一种单行方式。 It iterates through the list item by item, setting each element to lowercase, and then stripping trailing characters '"-,.:;??它逐项遍历列表,将每个元素设置为小写,然后去除尾随字符 '"-,.:;??

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM