0

我正在做一个项目,我试图从 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 方面有点新手,很抱歉打扰大家,但我很难找到关于搜索文本文件的预先编写的主题。谢谢!

最好的

4

1 回答 1

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 结合起来,您可能会拥有所需的东西。

于 2013-07-16T20:23:40.083 回答