https://www.mediawiki.org/wiki/Manual:Page_title指出了MediaWiki pageTitle可能不包含的条件。用这种方法看起来很难检查一个字符串是否为有效的MediaWiki PageTitle。
检查页面标题是否有效的正则表达式或类似的简单方法是什么?
到目前为止,我能找到的最好的东西是一些Java代码(来自https://github.com/MER-C/wiki-java/blob/master/src/org/wikipedia/Wiki.java)。我的目标语言是python。
/**
* Convenience method for normalizing MediaWiki titles. (Converts all
* underscores to spaces).
* @param s the string to normalize
* @return the normalized string
* @throws IllegalArgumentException if the title is invalid
* @throws IOException if a network error occurs (rare)
* @since 0.27
*/
public String normalize(String s) throws IOException
{
// remove leading colon
if (s.startsWith(":"))
s = s.substring(1);
if (s.isEmpty())
return s;
int ns = namespace(s);
// localize namespace names
if (ns != MAIN_NAMESPACE)
{
int colon = s.indexOf(":");
s = namespaceIdentifier(ns) + s.substring(colon);
}
char[] temp = s.toCharArray();
if (wgCapitalLinks)
{
// convert first character in the actual title to upper case
if (ns == MAIN_NAMESPACE)
temp[0] = Character.toUpperCase(temp[0]);
else
{
int index = namespaceIdentifier(ns).length() + 1; // + 1 for colon
temp[index] = Character.toUpperCase(temp[index]);
}
}
for (int i = 0; i < temp.length; i++)
{
switch (temp[i])
{
// illegal characters
case '{':
case '}':
case '<':
case '>':
case '[':
case ']':
case '|':
throw new IllegalArgumentException(s + " is an illegal title");
case '_':
temp[i] = ' ';
break;
}
}
// https://www.mediawiki.org/wiki/Unicode_normalization_considerations
String temp2 = new String(temp).trim().replaceAll("\\s+", " ");
return Normalizer.normalize(temp2, Normalizer.Form.NFC);
}
答案 0 :(得分:1)
如果您可以调用目标Wiki API进行规范化,那么这是对页面标题进行规范化的API调用示例:
归一化的标题不适用于/query/normalized/0/to
。您可以一次发送多个标题以用|
分隔它们进行标准化。
该示例摘自https://www.mediawiki.org/wiki/API:Query#Example_2:_Title_normalization。