计算XSLT中字符串中包含的单词的频率



如何计算字符串中包含的单词的频率?我必须使用XSLT 1.0

XML示例:

<a>
<b>Can you can a can as a canner can can a can?</b>
</a>

所以单词"can"在这个字符串中出现了六次?我可以数罐头吗?xD

我用了类似的东西,但是只得到"1">

<xsl:value-of select ="count(a/b[contains(.,'can')])" />
<<p>附加问题/strong>:如何计算"can";和";Can"但不是"罐头工人"。 ?

您可以使用以下示例作为起点:

XML>
<root>
<string>Can you can a can as a canner can can a can?</string>
</root>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:variable name="upper-case" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="lower-case" select="'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="punctuation" select="'.,:;!?'"/>
<xsl:template match="/root">
<results>
<xsl:for-each select="string">
<count>
<xsl:call-template name="count-word-occurrences">
<xsl:with-param name="text" select="translate(translate(., $upper-case, $lower-case), $punctuation, '')"/>
<xsl:with-param name="word">can</xsl:with-param>
</xsl:call-template>
</count>
</xsl:for-each>
</results>
</xsl:template>
<xsl:template name="count-word-occurrences">
<xsl:param name="text"/>
<xsl:param name="word"/>
<xsl:param name="delimiter" select="' '"/>
<xsl:param name="count" select="0"/>

<xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
<xsl:variable name="new-count" select="$count + ($token = $word)" />

<xsl:choose>
<xsl:when test="contains($text, $delimiter)">
<!-- recursive call -->
<xsl:call-template name="count-word-occurrences">
<xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
<xsl:with-param name="word" select="$word"/>
<xsl:with-param name="count" select="$new-count"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$new-count"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

结果

<?xml version="1.0" encoding="UTF-8"?>
<results>
<count>6</count>
</results>

警告:

  1. 大写到小写的转换仅限于小写ASCII字符;
  2. 标点符号列表不完整;
  3. 注意标点符号可以用代替空格(例如连字符)。

最新更新