【发布时间】:2012-12-27 11:04:54
【问题描述】:
我想让用户选择并打开多个文本并在文本中搜索完全匹配的内容。 我希望编码是 unicode。
如果我搜索“cat”,我希望它找到“cat”、“cat”、“.cat”,而不是“catalogue”。
我不知道如何让用户在所有文本中同时搜索两个词(“猫”或“狗”)?????? 也许我可以使用 RE?
到目前为止,我刚刚使用户可以插入包含要搜索的文本文件的目录的路径。现在我想让用户 (raw_input) 在所有文本中搜索两个单词,并且然后将结果(例如 document1.txt 中的“search_word_1”和“search_word_2”,document4.txt 中的“search_word_2”)打印并保存在单独的文档 (search_words) 中。
import re, os
path = raw_input("insert path to directory :")
ex_library = os.listdir(path)
search_words = open("sword.txt", "w") # File or maybe list to put in the results
thelist = []
for texts in ex_library:
f = os.path.join(path, texts)
text = open(f, "r")
textname = os.path.basename(texts)
print textname
for line in text.read():
text.close()
【问题讨论】:
-
你得到了什么?你期待什么?
-
for names in textname.split():只会为您提供文件基本名称中的字符列表。您需要将其更改为:for line in text.read():,然后您将遍历文本文件中的行。 -
不要使用
file作为变量名。 -
@BurhanKhalid:可以使用
file作为变量名。 Python 3 中没有内置file。您应该始终使用open而不是file打开文件。需要创建file的子类的情况很少见。 -
这是一个非常简单的python递归grep版本:gist.github.com/4387573