我有一个很多行的文件。格式如下,
//many lines of normal text
00.0000125 1319280 9.2 The Shawshank Redemption (1994)
//lines of text
0000011111 59 6.8 "$#*! My Dad Says" (2010) {You Can't Handle the Truce (#1.10)}
1...101002 17 6.6 "$1,000,000 Chance of a Lifetime" (1986)
我想将数据拆分为列1...101002,17,6.6,"$1,000,000 Chance of a Lifetime" (1986)
我尝试的程序是,
import re
f = open("E:/file.list");
reg = re.compile('[+ ].{10,}[+ ][+0-9].{3,}[+ ]')
for each in f:
if reg.match(each):
print each
print reg.split(each)
我不知道要使用的正则表达式是否正确答案。
答案 0 :(得分:1)
在这种情况下,匹配更容易,而不是拆分。
^\s*(\S+)\s+(\S+)\s+(\S+)\s+(.*)$
试试这个。看看演示。
http://regex101.com/r/oE6jJ1/47
import re
p = re.compile(ur'^\s*(\S+)\s+(\S+)\s+(\S+)\s+(.*)$', re.IGNORECASE | re.MULTILINE)
test_str = u"00.0000125 1319280 9.2 The Shawshank Redemption (1994)\n\n 0000011111 59 6.8 \"$#*! My Dad Says\" (2010) {You Can't Handle the Truce (#1.10)}\n 1...101002 17 6.6 \"$1,000,000 Chance of a Lifetime\" (1986)"
re.findall(p, test_str)
答案 1 :(得分:1)
>>> text="""0000011111 59 6.8 "$#*! My Dad Says" (2010) {You Can't Handle the Truce (#1.10)}
... 1...101002 17 6.6 "$1,000,000 Chance of a Lifetime" (1986)"""
>>> re.findall(r'([0-9\.]+)\s*([0-9]+)\s*([0-9\.]+)\s*(".*")',text)
[('0000011111', '59', '6.8', '"$#*! My Dad Says"'), ('1...101002', '17', '6.6', '"$1,000,000 Chance of a Lifetime"')]
答案 2 :(得分:1)
我改变了RegEx模式。
import re
f = open("file.txt");
reg = re.compile(r" (.{10}) *(\d*) *(\d*\.\d*) (.*)")
for each in f:
if reg.match(each):
print each
print reg.split(each)
答案 3 :(得分:1)
像
这样的东西>>> str='1...101002 17 6.6 "$1,000,000 Chance of a Lifetime" (1986)'
>>> re.findall(r'^([^ ]+)\s+([^ ]+)\s+([^ ]+)\s+(.*)', str)
[('1...101002', '17', '6.6', '"$1,000,000 Chance of a Lifetime" (1986)')]
答案 4 :(得分:1)
首先按split()
函数拆分行,然后将拆分列表(使用itertools.islice()
)从列表前导切换到括号中的数字(if re.match(r'\(\d+\)',j)
):< / p>
>>> s="""0000011111 59 6.8 "$#*! My Dad Says" (2010) {You Can't Handle the Truce (#1.10)}"""
>>> s.split()
['0000011111', '59', '6.8', '"$#*!', 'My', 'Dad', 'Says"', '(2010)', '{You', "Can't", 'Handle', 'the', 'Truce', '(#1.10)}']
>>> l=s.split()
>>> [list(islice(l,0,i+1)) for i,j in enumerate(l) if re.match(r'\(\d+\)',j)]
[['0000011111', '59', '6.8', '"$#*!', 'My', 'Dad', 'Says"', '(2010)']]
如果您的行在列表中(使用readlines()
读取文件):
>>> lines = ["""00.0000125 1319280 9.2 The Shawshank Redemption (1994)""","""0000011111 59 6.8 "$#*! My Dad Says" (2010) {You Can't Handle the Truce (#1.10)}""", """1...101002 17 6.6 "$1,000,000 Chance of a Lifetime" (1986)"""]
>>> [list(islice(line.split(),0,i+1)) for line in lines for i,j in enumerate(line.split()) if re.match(r'\(\d+\)',j)]
[['00.0000125', '1319280', '9.2', 'The', 'Shawshank', 'Redemption', '(1994)'], ['0000011111', '59', '6.8', '"$#*!', 'My', 'Dad', 'Says"', '(2010)'], ['1...101002', '17', '6.6', '"$1,000,000', 'Chance', 'of', 'a', 'Lifetime"', '(1986)']]