Skip to main content
 首页 » 编程设计

python之使用 "re.sub"在 python 中剥离代码

2025年05月04日15qq78292959

我读了这个: Stripping everything but alphanumeric chars from a string in Python

还有这个: Python: Strip everything but spaces and alphanumeric

不太明白,但我尝试了一下自己的代码,现在看起来像这样:

import re 
 
decrypt = str(open("crypt.txt")) 
 
crypt = re.sub(r'([^\s\w]|_)+', '', decrypt) 
 
print(crypt) 

当我运行脚本时,它会返回以下答案: C:\Users\Adrian\Desktop\python>python tick.py ioTextIOWrapper namecrypttxt moder encodingcp1252

我试图从文档中去掉所有额外的代码,只保留数字和字母,在文档中可以找到以下文本:http://pastebin.com/Hj3SjhxC

我正在尝试解决这里的作业: http://www.pythonchallenge.com/pc/def/ocr.html

有谁知道“ioTextIOWrapper namecrypttxt moder encodingcp1252”是什么意思? 我应该如何格式化代码以正确地从除字母和数字以外的所有内容中删除它?

真诚的

请您参考如下方法:

str(open("file.txt")) 并不像您想象的那样。 open() 返回一个文件对象。 str 为您提供该文件对象的字符串表示形式,不是文件的内容。如果您想读取文件的内容,请使用 open("file.txt").read()。

或者,更安全地,使用 with 语句:

with open("file.txt") as f: 
    decrypt = f.read() 
crypt = ...  
# etc.