【问题标题】:stripping away code in python using "re.sub"使用“re.sub”剥离python中的代码
【发布时间】:2013-01-04 06:09:49
【问题描述】:

我读到这个: 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 mode encodingcp1252

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

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

有人知道“ioTextIOWrapper namecrypttxt moder encodingcp1252”是什么意思吗? 我应该如何格式化代码以正确地将其从除字母和数字之外的所有内容中剥离出来?

真诚的

【问题讨论】:

  • 你也应该用regex标记这个

标签: python regex string formatting


【解决方案1】:

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

或者,更安全的是,使用with 声明:

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

【讨论】:

    【解决方案2】:

    您可以只搜索字母数字字符。像这样:

    print ''.join(re.findall('[A-Za-z]', decrypt))
    

    你还想要:

    decrypt = open("crypt.txt").read()
    

    【讨论】:

    • 我的代码中的“print ''.join(re.findall('[A-Za-z]', decrypt))”部分在哪里?感谢您解决我什至不知道我遇到的打开文件问题:)
    • 好吧,与其删除除字母之外的所有内容,不如只查找字母本身更容易。
    • [A-Z] 表示从 A 到 Z 的任意字母,与 a-z 相同,小写除外
    • 是的,但我的意思是我应该把它放在哪里?这就是我现在对代码所做的: import re decrypt = open("crypt.txt").read() print(''.join(re.findall('[A-Za-z]', decrypt)它会导致以下错误:C:\Users\Adrian\Desktop\python>python tick.py File "tick.py", line 12 ^ SyntaxError: unexpected EOF while parsing
    • 看起来你最后忘记了)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    相关资源
    最近更新 更多