我试图从python中删除一些我不希望在python中使用的字符,但据我所知,replace函数应该可以正常工作,但不是:(
顺便说一句(这只是一个简单的wordcount函数)
编码fileName = "simple.txt"
inputFile = open(fileName, "rb")
wordCount = {}
for line in inputFile:
splitted = line.split(" ")
for word in splitted:
word.replace('\n','') #It's not removing this chars from words
word.replace('?','') #Nor this ones
if word in wordCount:
wordCount[word] = wordCount[word] + 1
else:
wordCount[word] = 1
print wordCount
输入How many roads must a man walk down Before you call him a man? How
many seas must a white dove sail Before she sleeps in the sand? Yes,
how many times must the cannon balls fly Before they're forever
banned? The answer my friend is blowin' in the wind The answer is
blowin' in the wind.
Yes, how many years can a mountain exist Before it's washed to the
sea? Yes, how many years can some people exist Before they're allowed
to be free? Yes, how many times can a man turn his head Pretending he
just doesn't see? The answer my friend is blowin' in the wind The
answer is blowin' in the wind.
Yes, how many times must a man look up Before he can really see the
sky? Yes, how many ears must one man have Before he can hear people
cry? Yes, how many deaths will it take till he knows That too many
people have died? The answer my friend is blowin' in the wind The
answer is blowin' in the wind.
输出{'ears': 1, 'Yes,': 7, 'allowed': 1, 'knows\n': 1, 'sleeps': 1,
'people': 3, 'seas': 1, 'is': 6, '\n': 2, 'some': 1, 'it': 1, 'walk':
1, 'How': 2, 'see': 1, "blowin'": 6, 'have': 1, 'in': 7, 'roads': 1,
'up\n': 1, 'free?\n': 1, 'cry?\n': 1, 'really': 1, 'one': 1,
'mountain': 1, 'he': 4, 'just': 1, 'to': 2, "it's": 1, 'deaths': 1,
'washed': 1, 'head\n': 1, 'how': 7, 'down\n': 1, 'call': 1, 'take': 1,
'Pretending': 1, 'answer': 6, 'have\n': 1, 'white': 1, 'must': 5,
"doesn't": 1, 'friend': 3, 'can': 5, 'be': 1, 'sail\n': 1, 'his': 1,
'wind\n': 3, 'sea?\n': 1, 'cannon': 1, 'till': 1, 'see?\n': 1,
'wind.\n': 3, 'man?\n': 1, 'you': 1, 'banned?\n': 1, 'hear': 1, 'too':
1, 'sky?\n': 1, 'The': 6, 'sand?\n': 1, 'dove': 1, 'him': 1, 'man': 4,
'a': 6, "they're": 2, 'forever': 1, 'balls': 1, 'look': 1, 'fly\n': 1,
'many': 10, 'exist\n': 2, 'times': 3, 'will': 1, 'turn': 1, 'died?\n':
1, 'she': 1, 'the': 10, 'years': 2, 'my': 3, 'That': 1, 'Before': 7}
谢谢你!在