本书章节索引提取程序是否有改进?

时间:2019-06-12 03:09:15

标签: python

我正在尝试从包含多行书名的文件中提取章节索引。

这是一个样本

var pressTimer;

$("a").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() 
  {    fileChooser.click() // assume fileChoose is a file input element
       // This is suppressed by most browsers.
  },1000);
  return false; 
});

首先,我将其分成一个列表

rawlines = '''
1 A C++ Primer 1
1.1 Basic C++ Programming Elements 2
1.1.1 A Simple C++ Program 2
'''

然后,我匹配列表中的每个项目

raw_list = [y for y in (x.strip() for x in rawlines.splitlines()) if y]

现在,section_index_list = [] for i in raw_list: a = re.findall('\d{1}\.\d{1}\.\d{1}',i) if len(a): section_index_list.append(a[0]) continue a = re.findall('\d{1}\.\d{1}',i) if len(a): section_index_list.append(a[0]) continue a = re.findall('\d{1}',i) if len(a): section_index_list.append(a[0]) continue 存储了我需要的东西

section_index_list

工作已经完成,但我认为这段代码可能会有所改进。 有什么主意吗?

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题

rawlines = '''
1 A C++ Primer 1
1.1 Basic C++ Programming Elements 2
1.1.1 A Simple C++ Program 2
'''

raw_list = [y for y in (x.strip() for x in rawlines.splitlines()) if y]
res = list(map(lambda i: i.split(' ')[0], raw_list))

# ['1', '1.1', '1.1.1']

将所有内容放入函数中

def extractor(s):
    temp_list = [l for l in s.splitlines() if len(l)!=0]
    return list(map(lambda i: i.split(' ')[0], temp_list))

test = extractor(rawlines)
# ['1', '1.1', '1.1.1']

综合版本

def extractor(s):
    return [l.split(' ')[0] for l in s.splitlines() if len(l)!=0]

答案 1 :(得分:0)

我希望这会有所帮助。我猜它很简单:

/deep/ .dx-editor-cell .dx-texteditor .dx-texteditor-input {
    background: blue;
}