Python-从lis中删除标点符号

2024-09-29 21:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从文本文件中删除punc。

文本文件是这样的

ffff, hhhh, & tommorw home,
Have you from gone?

我在努力

punc=(",./;'?&-")

f = open('file.txt', 'r')

for line in f:
    strp=line.replace(punc,"")
    print(strp)

我需要输出:

ffff hhhh tommorw home

Have you from gone

这将返回每一行,但punc仍然存在>;可能需要一些帮助。谢谢


Tags: fromtxtyouhomehavelineopenfile
3条回答

使用str.translate从字符串中删除字符。

在Python 2.x中:

# first arg is translation table, second arg is characters to delete
strp = line.translate(None, punc)

在Python 3中:

# translation table maps code points to replacements, or None to delete
transtable = {ord(c): None for c in punc}
strp = line.translate(transtable)

或者,可以使用str.maketrans来构建transtable

# first and second arg are matching translated values, third arg (optional) is the characters to delete
transtable = str.maketrans('', '', punc)
strp = line.translate(transtable)
>>> import string
>>> with open('/tmp/spam.txt') as f:
...   for line in f:
...     words = [x.strip(string.punctuation) for x in line.split()]
...     print ' '.join(w for w in words if w)
... 
ffff hhhh tommorw home
Have you from gone
import string

str_link = open('replace.txt','r').read()

#str_link = "ffff, hhhh, & tommorow home, Have you from gone?"

punc = list(",./;'?&-")

for line in str_link:
    if line in punc:
        str_link = str_link.replace(line,"") 

print str_link

相关问题 更多 >

    热门问题