难以从Excel文件中读取文本

时间:2013-07-16 20:09:31

标签: excel text xlrd

我正在开展一个项目,我正在尝试从excel文件中搜索关键字的大量文本。这些关键字是各种格式的引用(例如XXXXXX,YYYY),然后还在文本中搜索包含作者姓氏的引文。在excel中,C列是作者的姓氏,D列是写作的文本。我正在使用xlrd,但我不知道如何使用列表“L”中的项目搜索列表“L1”中的项目。最后,我需要搜索列表“L1”(文本)进行引用,然后再次搜索L1以获取与L中相应单元格同名的引文(例如C3 = Smith,必须搜索D3以查找任何引用这个名字史密斯)。任何有关此任务的帮助,或我的任务的其他提示/方法将不胜感激!

以下是我目前搜索excel文件的代码。

from xlrd import open_workbook,cellname

book = open_workbook("C:\Python27\Doc\Book3.xls")
sheet = book.sheet_by_index(0)
for year in xrange(1900,2014):
    citation = str(year) or str(year) + ')' or '(' + str(year) + ')' or str(year) + ';'

firstc = sheet.col_values(2)
secondc = sheet.col_values(3)
L = [firstc]
L1 = [secondc]
if citation in L1:
    print 'citation ' + str(year)
if L in L1:
     print 'self-cite ' + str(year)
for item in L1:
    if citation in item:
        print item

我在python中有点新手,我为打扰你们而道歉,但我很难找到有关搜索文本文件的预先写好的主题。谢谢!

最佳

1 个答案:

答案 0 :(得分:0)

您无法查看L(列表)是否在L1中。您可以查看L中的项目是否在L1中。例如:

>>> s = 'abcde'
>>> b = ['a', 'f', 'g', 'b']
>>> b
['a', 'f', 'g', 'b']
>>> for i in b:
...    if i in s:
...     print i
...    else:
...     print "nope"
... 
a
nope
nope
b
>>> 

如果你有两个列表,你需要使用嵌套的for循环遍历这两个列表:

for i in b:
  for j in L1:
    do stuff

希望能给你一个开始。

ETA: 您可以使用enumerate来获取当前正在循环的项目的索引,并使用它来进入第二个列表中的右侧行:

>>> b = ['a', 'f', 'g', 'b']
>>> L1 = ['worda', 'words including b', 'many many words', 'a lot more words']

>>> for i, j in enumerate(b):
...   if j in L1[i]: 
...     print j
...   else:
...     print i, j
a
1 f
2 g
3 b
>>> 

将其与row_values结合使用,您可能拥有所需的内容。