Python 删除逗号和句点

Python 删除逗号和句点,python,file-io,stripping,Python,File Io,Stripping,我目前正在尝试输入一个文本文件,将每个单词分开并组织成一个列表 当前的问题是从文本文件中去掉逗号和句点 我的代码如下: #Process a '*.txt' file. def Process(): name = input("What is the name of the file you would like to read from? ") file = open( name , "r" ) text = [word for line in file for wo

我目前正在尝试输入一个文本文件,将每个单词分开并组织成一个列表

当前的问题是从文本文件中去掉逗号和句点

我的代码如下:

#Process a '*.txt' file.
def Process():
    name = input("What is the name of the file you would like to read from? ")

    file = open( name , "r" )
    text = [word for line in file for word in line.lower().split()]
    word = word.replace(",", "")
    word = word.replace(".", "")

    print(text)
我目前得到的输出是:

['this', 'is', 'the', 'first', 'line', 'of', 'the', 'file.', 'this', 'is', 'the', 'second', 'line.']
如您所见,单词“file”和“line”的末尾有一个句号

我正在阅读的文本文件是:

这是文件的第一行

这是第二行


提前谢谢。

这些行没有效果

word = word.replace(",", "")
word = word.replace(".", "")
只需将您的列表组件更改为:

[word.replace(",", "").replace(".", "") 
 for line in file for word in line.lower().split()]

也许
strip
replace

def Process():
    name = input("What is the name of the file you would like to read from? ")

    file = open(name , "r")
    text = [word.strip(",.") for line in file for word in line.lower().split()]
    print(text)
>>>帮助(str.strip) 有关方法\u描述符的帮助: 带(…) S.strip([chars])->字符串或unicode 返回带前导和尾随的字符串S的副本 删除空白。 如果给定了字符而不是无,则删除字符中的字符。 如果字符是unicode,则在剥离之前将字符转换为unicode 试试这个:

 chars = [',', '.']

 word.translate(None, ''.join(chars))
用于蟒蛇3

 chars = [',', '.']
 word.translate({ord(k): None for k in chars})

他们曾经有过影响吗?出于某种原因,我的老师让我们看它们?在这种情况下它们没有效果,因为在完成列表理解后,
word
将始终是对单词列表中最后一个单词的引用@jamylak版本的代码正确地替换了列表中的每个单词。哈,酷。非常感谢!我现在就试试这个。。。它能用吗。
 chars = [',', '.']
 word.translate({ord(k): None for k in chars})