在我的.html文件中使用python切片字符串

时间:2014-05-01 18:43:59

标签: python html django slice

我正在阅读excel文件并使用python进行搜索。此搜索返回用户输入的三个不同变量。因此,如果用户想要搜索apple,orange和banana,网页将打印出该单词所在的excel文件的整个单元格。我想要做什么,因为有时候单元格很长并且有多个句子,用于识别搜索到的单词所在的位置,如果输出的运行时间长于此,则将其分为前20个单词和后20个单词。

我将这些值保存为第一,第二和第三个发送到数据库的值,然后搜索excel文件。

在我的.html页面中,我有它,所以它在html部分以这种方式读取,用户输入他们想要搜索的单词(然后在数据库中存储为第一,第二和第三)

First term:<input type="text" name="first" size="10" style="font-size: 25px; direction: rtl;" value="{{ first }}"> &nbsp;&nbsp;&nbsp;

Second Term:<input type="text" name="second" size="10" style="font-size: 25px; direction: rtl;" value="{{ second }}">  &nbsp;&nbsp;&nbsp;

third term:<input type="text" name="third" size="10" style="font-size: 25px; direction: rtl;" value="{{ third }}"> 

然后,打印出所有输出的部分是:

{% for key,value,line in box %}
<form id="form2" name="form2" action="{{URL_ROOT}}/search/" method="post">
{% csrf_token %}
<table class='table' border="0" width="100%">
<tr>

<td class='td-center' width="90%" style="direction: rtl;">{{ value }}</td>

如何截断/切片{{value}},就像我在搜索过的术语之前和之后用20描述的那样?价值是输出的。

我知道我可以从一个数字位置切片,比如值:切片:&#39; 20:&#39;但我希望它从搜索到的变量中分割出第一,第二和第三

2 个答案:

答案 0 :(得分:1)

仅供参考我不熟悉您的设置,但这是一个可能的解决方案。

也许您可以在空格上拆分单元格内容并将单词存储到数组中。然后找到您的搜索字词并选择words[index - 20:index + 20]之类的切片。 (当然,如果您的搜索词之前或之后少于20个单词,请务必进行正确的索引检查。)

答案 1 :(得分:1)

您可能希望编写自定义模板过滤器来执行操作,这是您可以使用的功能。我使用您的开头行作为文本测试块,并将“倍数”作为我的搜索词:

def from_term(text, term):
    s = text.split(term)
    before = ' '.join(s[0].split()[-20:])
    after = ' '.join(s[1].split()[:20])
    return before + ' ' + term + ' ' + after

>>> text = "I'm reading in an excel file and doing a search in it with python. This search returns three different variables that the user inputs. So, if the user wants to search for apple, orange, and banana, the webpage will print out the whole cell of the excel file that that word is located in. What I want to do, since sometimes the cell is really long and has multiple sentences, is to identify where the searched word is and slice it 20 words before and 20 words after, if the output runs longer than that."
>>> term = 'multiple'
>>> from_term(text, 'multiple')
'that that word is located in. What I want to do, since sometimes the cell is really long and has multiple sentences, is to identify where the searched word is and slice it 20 words before and 20 words after, if'