使用替换字母字符串.标点符号在for循环中

2024-10-01 09:34:30 发布

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

简而言之,我试图用空格替换单词中的标点符号。在

例如,文本文档输出在处理后将没有这样的标点符号。在

Meep Meep! I tot I taw a putty tat. I did I did I did taw a putty tat Shsssssssssh I am hunting wabbits Heh Heh Heh Heh Its a fine day to hunt wabbits Heh Heh Heh Stop its wabbit huntin season Huntin Wabbits The finitive guide 101 ways to kook wabbit

没有改动它看起来像这样。在

问题5.txt中的文本

Meep Meep! I tot I taw a putty tat. I did! I did! I did taw a putty tat. Shsssssssssh ... I am hunting wabbits. Heh Heh Heh Heh ... It's a fine day to hunt wabbits! ... Heh Heh Heh ... Stop - it's wabbit huntin season! Huntin Wabbits: The finitive guide 101 ways to kook wabbit.

这是一个练习,所以我被告知要使用。replace和for循环。在

import string
infile = open('question5.txt', 'r')

lines = infile.readlines()
lines = str(lines)
for words in lines:
    for letters in words:
        letters.replace(string.punctuation,' ')
        print(letters)

如能协助解决这一问题,我们将不胜感激。在

注意,在你的建议和一些研究之后,如果有人关注结果的话,我花了很多时间来研究这个问题。谢谢各位波浪

^{pr2}$

Tags: toforlines标点符号didputtyletterswabbit
3条回答

这样更好:

import string as st

trans = st.maketrans(st.punctuation, ' '*len(st.punctuation))
with open('question5.txt', 'r') as f:
    for line in f:
        print line.translate(trans)

首先,作为elyaseshows,您应该使用with构造,或者应该在末尾关闭文件。而且,正如他所示,在动态读取和处理文本文件时,您永远不要使用.readlines()。只用于循环文件对象的内容。它是逐行迭代的(包括结尾\n)。在

另一个问题是lines = str(lines)。实际上,您的lines最初是一个字符串列表。str将其转换为一个类似"['Meep...', 'wabits...', 'huntin...']"的字符串。首先循环该字符串,得到单个字符(作为单字符字符串)。将其命名为words并不会改变现实。(如果您真的想把单词从行中去掉,您应该使用类似for word in line.split():的东西。)

然后,在单个字符中循环第二次,再次获得单个字符(即循环只循环一次,不添加任何功能)。在

接下来,.replace()返回replacement的结果,但它不修改参数。你想把结果赋给某个变量。无论如何,您不能使用string.punctuation作为要替换的旧字符串,因为在源文本中永远找不到它。暴力解决方案必须循环使用标点符号字符串并替换单个字符。在

总而言之,letters仍然包含单个字符,不能替换。然后打印单个字符。print函数添加新行。通过这种方式,您可以看到原始内容呈现为字符串表示的字符串/行列表,这些字符串/行是以中文方式自上而下一列书写的。在

最后,the string.punctuation只是一个字符串常量。在

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

您可以通过不导入string模块来简化代码(如果没有这样做的话),并将自己的字符串文本与应该被视为标点字符的字符一起使用。在

我不能百分之百的肯定,因为你的样本输出仍然包括一些标点错误,也许?在

在Python2.x中,您可以尝试以下操作,因为它实际上并没有用空格替换,而不仅仅是删除标点符号。在

from string import punctuation
with open('question5.txt') as fin:
    test = fin.read()

new_text = test.translate(None, punctuation)

或者,使用正则表达式:

^{pr2}$

仅使用循环的示例:

new_string = ''
for ch in old_string:
    if ch not in punctuation:
        new_string += ch

通过将punctuation放入一个集合中(或使用上述方法),可以提高效率

相关问题 更多 >