我写了一个脚本来打印包含圣经txt文件中特定单词的行。问题是我无法使用该行获得确切的单词而是打印该单词的所有变体。
例如。如果我搜索“am”,它会打印包含“lame”,“name”等字样的句子。 相反,我希望它只打印只有“am”的句子
即“我是你的救世主”,“我在这里”等等。
以下是我使用的代码:
import re
text = raw_input("enter text to be searched:")
shakes = open("bible.txt", "r")
for line in shakes:
if re.match('(.+)' +text+ '(.+)', line):
print line
答案 0 :(得分:1)
这是完成任务的另一种方法,虽然它不能很好地遵循您当前的方法,但它可能会有所帮助。
我输入的test.txt文件有四个句子:
classes/Link.php
运行程序时,请包含文本文件。在命令行中,它看起来像:
This is a special cat. And this is a special dog. That's an average cat. But better than that loud dog.
这是随附的file.py:
python file.py test.txt
对于关键字“cat”,返回:
import fileinput
key = raw_input("Please enter the word you with to search for: ")
#print "You've selected: ", key, " as you're key-word."
with open('test.txt') as f:
content = str(f.readlines())
#print "This is the CONTENT", content
list_of_sentences = content.split(".")
for sentence in list_of_sentences:
words = sentence.split(" ")
for word in words:
if word == key:
print sentence
(注意句号不再存在)。
答案 1 :(得分:0)
我想如果你在CREATE PROCEDURE [dbo].[CompareSchemaScript]
(
@ix_sys_error int OUTPUT
)
AS
BEGIN TRY
DECLARE @LogError INT, @PrimaryKey INT,@ErrorMessage nvarchar(2000)
EXEC log_ins @LogError, @PrimaryKey,5,1,NULL,1,'Script Started'
ALTER SCHEMA Database1.tables TRANSFER Database2.tables;
EXEC log_ins @LogError, @PrimaryKey,7,1,NULL,1,'Script Completed Successfully'
END TRY
BEGIN CATCH
SELECT @ix_sys_error = ERROR_NUMBER()
SELECT @ErrorMessage = ERROR_MESSAGE()
EXEC ix_sys_event_log_ins @LogError, @PrimaryKey,6,1,NULL,1,@ErrorMessage,NULL
END CATCH
IF (@ix_sys_error !=0)
RETURN 1
ELSE
RETURN 0
END
之外的字符串中放置这样的空格:
text
如果我正确理解代码中发生了什么,那就可以解决问题。
答案 2 :(得分:0)
re.findall可能很有用:
print re.findall(r"([^.]*?" + text + "[^.]*\.)", shakes.read())
甚至没有正则表达式:
print [sentence + '.' for sentence in shakes.split('.') if text in sentence]
阅读此文本文件:
I am your saviour. Here I am. Another sentence.
Second line.
Last line. One more sentence. I am done.
两者都给出相同的结果:
['I am your saviour.', ' Here I am.', ' I am done.']