简而言之,我试图用空格替换行内单词中的任何标点符号。
例如,一旦处理,文本文档输出将没有像这样的标点符号。
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)
如能协助解决问题,我们将不胜感激。
请注意您的建议和一些研究后,如果有人关注结果,我会在更多小时后结束。谢谢你们 Waves
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()
请您参考如下方法:
这样更好:
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)
