简而言之,我试图用空格替换行中的任何标点符号。
例如,文本文档输出一旦处理,就没有像这样的标点符号。
Meep Meep!我说的是油灰。我确实吃了一只灰泥,Shsssssssssh,我正在猎杀wabbit,呵呵,这是一个狩猎的好天气,呵呵,停止它的wabbit hunt季节,hunt wabbit,最后的指南101的方法来玩wabbit。
没有改变,它看起来是这样的。
问题5.txt
Meep Meep!我说的是油灰。我做到了!我做到了!我确实吃了个油灰。嘘嘘..。我在打猎。呵呵..。今天是打猎的好天气!..呵呵..。停-现在是流浪汉季节!Huntin :最后的指导101的方法来搞笑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)如能在解决这一问题方面提供任何协助,将不胜感激。
注意,在你的建议和一些研究之后,如果有人在关注结果,我会在许多小时后结束。谢谢各位Wave
import string
infile = open('question5.txt', 'r')
lines = infile.readlines()
def word_count(list):
count = 0
list = str(list)
for lines in list:
list = list.replace('.',' ')
list = list.replace(',',' ')
list = list.replace('-',' ')
split = list.split()
print (split)
for words in split:
count = count + 1
return count
for line in lines:
count = word_count(line)
print(count)
infile.close()发布于 2013-05-27 07:34:13
这样做更好:
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)发布于 2013-05-27 08:32:07
我不是百分之百肯定,因为你的样本输出仍然包括一些标点符号-也许?
在Python2.x中,您可以尝试以下操作,因为它实际上并不是用空格替换的,而不仅仅是删除标点符号。
from string import punctuation
with open('question5.txt') as fin:
test = fin.read()
new_text = test.translate(None, punctuation)或者,使用正则表达式:
import re
new_text = re.sub('[' + re.escape(punctuation) + ']+', '', test)仅使用循环的示例:
new_string = ''
for ch in old_string:
if ch not in punctuation:
new_string += ch通过将punctuation放在一个集合中(或使用上述方法),可以提高效率。
发布于 2013-05-27 09:35:09
首先,作为elyase shows,您应该使用with构造,或者在结束时关闭文件。此外,正如他所展示的,在读取文本文件并动态处理它时,您不应该使用.readlines()。只是为了-循环遍历文件对象的内容。它是逐行迭代的(包括结束的\n)。
另一个问题是lines = str(lines)。实际上,您的lines最初是一个字符串列表。str将其转换为一个类似于"['Meep...', 'wabits...', 'huntin...']"的字符串。您首先遍历该字符串--获得单个字符(作为单字符字符串)。将它命名为words并不会改变现实。(如果你真的想把单词去掉,你应该使用像for word in line.split():这样的词。)
然后,在单个字符中循环第二次--再次获得单个字符(即循环只循环一次,不添加任何功能)。
接下来,.replace()返回替换的结果,但是它不修改参数。您希望将结果赋值给某个变量。无论如何,您不能使用string.punctuation作为要替换的旧字符串,因为它永远不会在源文本中找到。强力解决方案必须遍历标点符号字符串并替换单个字符。
总之,letters仍然包含单个字符--没有替换。然后你打印出一个字符。print函数添加换行符。通过这种方式,您可以看到以中文方式编写的字符串/行列表的字符串表示形式呈现的原始内容--一列上/下一列。
最后,the string.punctuation只是一个字符串常量。
>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'您可以通过不导入string模块来简化代码(如果您没有这样做的话),并使用您自己的字符串文字和应该被视为标点符号的字符。
https://stackoverflow.com/questions/16768219
复制相似问题