![](/img/trans.png)
[英]Double quotes on a regex patter string causing failure of regular expression search
[英]Search for quotes with regular expression
我正在尋找一種方法來搜索文本文件中作者的報價,然后打印出來。 到目前為止,我的腳本是:
import re
#searches end of string
print re.search('"$', 'i am searching for quotes"')
#searches start of string
print re.search('^"' , '"i am searching for quotes"')
我想做什么
import re
## load text file
quotelist = open('A.txt','r').read()
## search for strings contained with quotation marks
re.search ("-", quotelist)
## Store in list or Dict
Dict = quotelist
## Print quotes
print Dict
我也試過
import re
buffer = open('bbc.txt','r').read()
quotes = re.findall(r'.*"[^"].*".*', buffer)
for quote in quotes:
print quote
# Add quotes to list
l = []
for quote in quotes:
print quote
l.append(quote)
開發一個正則表達式,使其與您希望在帶引號的字符串中看到的所有預期字符匹配。 然后在re
使用python方法findall
查找所有匹配項。
import re
buffer = open('file.txt','r').read()
quotes = re.findall(r'"[^"]*"',buffer)
for quote in quotes:
print quote
在“和”之間進行搜索需要unicode-regex搜索,例如:
quotes = re.findall(ur'"[^\u201d]*\u201d',buffer)
對於使用“和”交替使用引號終止的文檔
quotes = re.findall(ur'"[^"^\u201d]*["\u201d]', buffer)
您不需要正則表達式來查找靜態字符串。 您應該使用以下Python慣用法來查找字符串:
>>> haystack = 'this is the string to search!'
>>> needle = '!'
>>> if needle in haystack:
print 'Found', needle
創建列表非常簡單-
>>> matches = []
存儲比賽也很容易...
>>> matches.append('add this string to matches')
這應該足以讓您入門。 祝好運!
解決以下評論的附錄...
l = []
for quote in matches:
print quote
l.append(quote)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.