在Python中打印第5个单词

时间:2017-11-28 15:24:49

标签: python

我试图找出SQL文件中一串字后的第5个字。

string = INSERT INTO record

SQL文件:

LOCK TABLES `zone1` WRITE;

/*!ALTER TABLE `zone1` DISABLE KEYS */;

/*!ALTER TABLE `zone1` ENABLE KEYS */;

UNLOCK TABLES;
--
-- 
--
LOCK TABLES `zone2` WRITE;

/*!ALTER TABLE `zone2` DISABLE KEYS */;

/*!ALTER TABLE `zone2` ENABLE KEYS */;

UNLOCK TABLES;

INSERT INTO record VALUES ('All', 'people', 'seems', 'to', 'need', 'data', 'processing'),('Randomly','words','picked','to','complete','the','sentence')

INSERT INTO record VALUES ('1', '2', '3', '4', '5', '6', '7')

INSERT INTO record VALUES ('8', '9', '10', '11', '12', '13', '14')

 LOCK TABLES `zone3` WRITE;

/*!ALTER TABLE `zone3` DISABLE KEYS */;

/*!ALTER TABLE `zone3` ENABLE KEYS */;

UNLOCK TABLES;

--
-- 
--
LOCK TABLES `zone4` WRITE;

/*!ALTER TABLE `zone4` DISABLE KEYS */;

/*!ALTER TABLE `zone4` ENABLE KEYS */;

UNLOCK TABLES;

代码

import re
import fileinput
import sqlite3

fd=open('dump.sql','r')
filesql=fd.read()
fd.close()

string='INSERT INTO record'

def words(line):
    return re.sub(r'[\(\)\';]', '', line.strip()).split()

with open('dump.sql','r') as dump:
    for line in dump:
        if string in line:
            tail=line.split(string)[1]
            for group in tail.split("),("):
                print words(tail)[3] 

当我运行此代码时,我得到以下输出:

seems,seems,3,10,

我期待得到:

seems,picked,3,10,

有人可以告诉我我的代码有什么问题吗?

提前谢谢你, 丹

3 个答案:

答案 0 :(得分:1)

这个正则表达式起作用

import re

with open('dump.sql', 'r') as f:
    s = f.read()

matches = re.findall('\((\'[^\']*\',\s*){3}', s)
for match in matches:
    print(match)

答案 1 :(得分:0)

您可以计算字符串的起始区域,然后打印它后面的所有内容。
例如:

stringA = "Hello World My name is Robot Tim, and who are you?"

# Find the character position to start.
n = stringA.index(stringA.split()[5]);
#print(n);

stringB = stringA[n:]
print(stringB);

答案 2 :(得分:0)

试试这个

我不知道它是否适用于你所有的sql文件......

string = 'INSERT INTO record VALUES'

with open('dump.sql', 'r') as dump:
    for line in dump:
        if string in line:
            tail = line.split(string)[1]
            for group in tail.split("),("):
                group = group.replace("\'", "").replace("(", "").replace(")\n", "")
                print(group.split(",")[2].strip())

输出:

seems
picked
3
10
>>> 

在列表中获取结果

如果您想将结果列入清单

string = 'INSERT INTO record VALUES'
l = []
with open('dump.sql', 'r') as dump:
    for line in dump:
        if string in line:
            tail = line.split(string)[1]
            for group in tail.split("),("):
                group = group.replace("\'", "").replace("(", "").replace(")\n", "")
                print(group.split(",")[2].strip())
                l.append(group.split(",")[2].strip())