我使用microsoft word(查找和替换)解决了python挑战#2但是当我使用python时,我失败了,因为这段代码不起作用......
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
f = str(f)
f = str.replace(f, '!','')
f = str.replace(f, '@','')
f = str.replace(f, '#','')
f = str.replace(f, '$','')
f = str.replace(f, '%','')
f = str.replace(f, '^','')
f = str.replace(f, '&','')
f = str.replace(f, '*','')
f = str.replace(f, '(','')
f = str.replace(f, ')','')
print(f)
研究:它将打印出该文件的属性。为什么不提供信息?而且,我怎么能改变它?我试过f.open()
和" f"。我已经在这几个小时内多次更改了代码(我认为是3),但是这段代码仍然无效。
答案 0 :(得分:4)
您需要使用f = f.read()
:
f = str(f)
将显示文件对象的字符串表示形式,如:
<open file 'C:\\Python34\\Python Challenge\\Q2\\Q2.txt"', mode 'r' at 0x7f76a5a26e40>
然后使用str.translate
删除字符:
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
f = f.read()
f = f.translate(None,"!@#$%&()*^")
print(f)
对于python 3,我们需要使用要替换的字符的ord
创建一个dict映射,并将其传递给translate:
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
f = f.read()
# {ord(ch):"" for ch in "!@#$%&()*^"}
f = f.translate({64: '', 33: '', 35: '', 36: '', 37: '', 38: '', 40: '', 41: '', 42: '', 94: ''})
print(f)
答案 1 :(得分:2)
如果您说f = str(f)
正在阅读 f
,那么您将获得文件对象。准确地说是一串。然后你要替换它没有的字符,并将其打印出来。
您需要让f
成为文件的内容:
with open("PythonChallenge2.txt") as f:
f = str(f.readlines()) ##<-- Changed this to actually set f to the file contents, not the file object
f = str.replace(f, '!','')
f = str.replace(f, '@','')
f = str.replace(f, '#','')
f = str.replace(f, '$','')
f = str.replace(f, '%','')
f = str.replace(f, '^','')
f = str.replace(f, '&','')
f = str.replace(f, '*','')
f = str.replace(f, '(','')
f = str.replace(f, ')','')
print(f)
添加:
f = str.replace(f, '[','')
f = str.replace(f, ']','')
f = str.replace(f, '{','')
f = str.replace(f, '}','')
f = str.replace(f, '+','')
f = str.replace(f, '_','')
f = str.replace(f, '\\n','')
给你一个几乎显而易见的答案。
答案 2 :(得分:1)
因为这里没有人提到re
解决方案
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
print re.sub("!@#$%&()*^","",f.read())
答案 3 :(得分:0)
您可以使用搜索创建字典并替换字符串。
然后搜索并替换该项目中的每个项目。
replace_dict = {'!':'', '@':'', '#':'', '$':'', '%':'', '^':'', '&':'', '*':'', '(':'', ')':''}
with open("C:\\Python34\\Python Challenge\\Q2\\Q2.txt") as f:
content = f.read()
print content # <---print the original content
for key, value in replace_dict.items():
content = content.replace(key, value)
print content # <---print the modified content