我想申请正则表达式的文件的内容,而将整个文件加载到一个字符串。 RegexObject将第一个参数作为字符串或缓冲区。有没有办法将文件转换成缓冲区?如何将正则表达式应用于文件的内容?
2
A
回答
2
报价:
缓冲区对象不是直接通过 Python语法支持,但可以 通过调用内置 功能缓冲()创建的。
和其他一些有趣的部分:
缓冲液(对象[,偏移,大小]])
对象参数必须是 支持缓冲器呼叫接口的对象 (如字符串,数组和缓冲区)
名File对象没有实现缓冲界面 - 让你不得不改变其内容要么转换为字符串(f.read()
)或成阵列(使用mmap为该)。
4
1
搜索读入行的文件在一个时间并应用REG EXP到该行。似乎被堆叠起来处理字符串。 http://docs.python.org/library/re.html包含更多的细节,但我无法找到有关缓冲区的任何内容。从Python的文档
+0
唯一的问题是如果正则表达式匹配跨行(`/ foo \ nbar /`)... – ircmaxell 2011-02-07 20:00:26
0
进行缓冲自己。如果正则表达式匹配块的一部分,则从该块中删除该部分,继续使用未使用的部分,读取下一个块,重复。
如果正则表达式被设计为一个特定的理论最大的,对什么都不匹配,缓冲是在执法机关一样大的情况下,清除缓冲区,在接下来的块读取。一般来说,正则表达式不是用来处理非常大的数据块的。正则表达式越复杂,它所做的回溯越多。
0
下面的代码演示:
- 打开文件
- 文件
- 在求只读取文件
- 使用正则表达式匹配的模式
的一部分假设:所有的句子是个Ë相同长度
# import random for randomly choosing in a list
import random
# import re for regular expression matching
import re
#open a new file for read/writing
file = open("TEST", "r+")
# some strings to put in the sentence
typesOfSentences = ["test", "flop", "bork", "flat", "pork"]
# number of types of sentences
numTypes = len(typesOfSentences)
# for i values 0 to 99
for i in range(100):
# Create a random sentence for example
# "This is a test sentence 01"
sentence = "This is a %s sentence %02d\n" % (random.choice(typesOfSentences), i)
# write the sentence to the file
file.write(sentence)
# Go back to beginning of file
file.seek(0)
# print out the whole file
for line in file:
print line
# Determine the length of the sentence
length = len(sentence)
# go to 20th sentence from the beginning
file.seek(length * 20)
# create a regex matching the type and the number at the end
pathPattern = re.compile("This is a (.*?) sentence (\d\d)")
# print the next ten types and numbers
for i in range(10):
# read the next line
line = file.readline()
# match the regex
match = pathPattern.match(line)
# if there was a match
if match:
# NOTE: match.group(0) is always the entire sentence
# Print type of sentence it was and it's number
print "Sentence %02d is of type %s" % (int(match.group(2)), match.group(1))
相关问题
- 1. 如何将css应用于基于正则表达式的div内容
- 2. 如何基于正则表达式将文件内容分为不同的组?
- 3. 正则表达式:如何从内容
- 4. 使用正则表达式将文件夹内容写入CSV
- 5. 基于正则表达式拆分文件内容:python
- 6. 的Javascript正则表达式 - 如何基于正则表达式
- 7. Ant正则表达式替换文件内容的模式
- 8. 正则表达式的内容
- 9. 恢复内容的正则表达式
- 10. 如何使用正则表达式获取内部html内容
- 11. 如何将正则表达式应用于多行?
- 12. 如何将正则表达式应用于多行?
- 13. 正则表达式匹配的bash文件的全部内容
- 14. 作为grep的正则表达式的文件内容
- 15. 正则表达式用于匹配括号之间的内容
- 16. 用于剥离HTML标记和内容的正则表达式
- 17. 正则表达式适用于html外的大括号内容
- 18. 用于匹配方法内容的正则表达式
- 19. 正则表达式匹配正则表达式模式外的所有内容
- 20. 搜索文件内容的正则表达式匹配
- 21. 在文件中匹配正则表达式的内容?
- 22. java在文件内容中的正则表达式
- 23. 如何使用正则表达式检索DIV的内容?
- 24. 如何使用jQuery解析正则表达式的内容?
- 25. SED正则表达式用PHP正则表达式不兼容
- 26. 正则表达式内容类型
- 27. 正则表达式:HTML,内容
- 28. 内容URL正则表达式
- 29. 正则表达式查找内容
- 30. 正则表达式提及HTML内容
你试图将正则表达式应用到整个文件 - 我。e试图将整个文件与您的正则表达式匹配 - 或者您是否试图逐行匹配文件或以其他一些大小的块进行匹配? – 2011-02-07 19:29:05