我试图用Python编写代码,从两个关键字之间的所有单词中打印出来。
static void Main(string[] args)
{
string Parameter = args[0].ToLower().ToString().Replace(Settings.Default.ReplaceText.ToLower(), "");
string Ext = Settings.Default.PostExtn;
string url = Settings.Default.UrlPost + "/" + Parameter + "." + Ext;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
string result;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
RawPrinterHelper.SendValueToPrinter(Settings.Default.PrinterName, Encoding.ASCII.GetBytes(result));
return;
}
想要打印出“以打印所有内容”
答案 0 :(得分:2)
方法略有不同,让我们创建一个列表,每个元素都是句子中的单词。然后,我们使用list.index()
来查找start
和end
单词在句子中的哪个位置。然后,我们可以在这些索引之间返回列表中的单词。我们希望它以字符串形式而不是列表形式返回,因此我们join
将它们与空格一起。
# list of words ['This', 'is', 'a', 'test', ...]
words = scenario.split()
# list of words between start and end ['to', 'print', ..., 'the']
matching_words = words[words.index(start)+1:words.index(end)]
# join back to one string with spaces between
' '.join(matching_words)
结果:
to print out all the
答案 1 :(得分:0)
将字符串分割开,然后逐字遍历查找两个关键字所在的索引。一旦有了这两个索引,就可以将这些索引之间的列表合并为一个字符串。
scenario = 'This is a test to see if I can get Python to print out all the words in between Python and words'
start_word = 'Python'
end_word = 'words'
# Split the string into a list
list = scenario.split()
# Find start and end indices
start = list.index(start_word) + 1
end = list.index(end_word)
# Construct a string from elements at list indices between `start` and `end`
str = ' '.join(list[start : end])
# Print the result
print str
答案 2 :(得分:0)
最初的问题是您要遍历scenario
字符串,而不是将其拆分为单独的单词(使用scenario.split()
),但是还有其他问题切换到搜索末尾一旦找到开始,就改为单词,相反,您可能想使用索引来找到两个字符串,然后对该字符串进行切片
scenario = "This is a test to see if I can get Python to print out all the words in between Python and words"
start = "Python"
end = "words"
start_idx = scenario.index(start)
end_idx = scenario.index(end)
print(scenario[start_idx + len(start):end_idx].strip())
答案 3 :(得分:0)
您可以使用简单的regex
import re
txt = "This is a test to see if I can get Python to print out all the words in between Python and words"
x = re.search("(?<=Python\s).*?(?=\s+words)", txt)
这是正在使用的正则表达式-> REGEX101