[英]regular expressions in python script
我是python的新手。 我需要使用正則表達式在包含這些元音的列表中找到單詞。 以下無效。 誰能看到需要糾正的內容? 謝謝。
import re
file = open('wordlist.txt', 'r')
print re.findall('[aie]', file)
我收到此錯誤:
Traceback (most recent call last):
File "C:\Python27\MyScripts\script2.py", line 3, in ` <module>
print re.findall('[aie]', file)
File "C:\Python27\lib\re.py", line 181, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
這是單詞表中的內容,我可以使用此列表進行檢索:
file = open('wordlist.txt', 'r')
print file.read()`
打印輸出:
ae
The
Intelligent
Assistance
Revolution
may
not
be
televised
but
it
will
definitely
be
re.findall()
不接受文件對象,因為錯誤表明您需要傳遞字符串或緩沖區,因此您可以使用file.read()
將文件作為字符串對象傳遞給findall()
函數:
print re.findall('[aie]', file.read())
或者,如果您要處理大文件而拒絕一次讀取文件,則可以采用一種更加Python化的方式,您可以遍歷文件,並根據需要對每行使用re.search
或re.fildall
。
with open('wordlist.txt') as f:
for line in f:
#do stuff with line
應該這樣做:
import re
file = open('wordlist.txt', 'r')
print re.findall('[aie]', file.read())
該錯誤是由於您嘗試在文件對象上實現而不是內容而導致的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.