尝试将PHP函数转换为Python,我是python的新手,tthats我试过的
Python - >
def stopWords(text, stopwords):
stopwords = map(to_lower(x),stopwords)
pattern = '/[0-9\W]/'
text = re.sub(pattern, ',', text)
text_array = text.partition(',');
text_array = map(to_lower(x), text_array);
keywords = []
for term in text_array:
if(term in stopwords):
keywords.append(term)
return filter(None, keywords)
stopwords = open('stop_words.txt','r').read()
text = "All words in the English language can be classified as one of the eight different parts of speech."
print(stopWords(text, stopwords))
PHP - >
function stopWords($text, $stopwords)
{
// Remove line breaks and spaces from stopwords
$stopwords = array_map(
function ($x)
{
return trim(strtolower($x));
}
, $stopwords);
// Replace all non-word chars with comma
$pattern = '/[0-9\W]/';
$text = preg_replace($pattern, ',', $text);
// Create an array from $text
$text_array = explode(",", $text);
// remove whitespace and lowercase words in $text
$text_array = array_map(
function ($x)
{
return trim(strtolower($x));
}
, $text_array);
foreach($text_array as $term)
{
if (!in_array($term, $stopwords))
{
$keywords[] = $term;
}
};
return array_filter($keywords);
}
$stopwords = file('stop_words.txt');
$stopwords = file('stop_words.txt');
$text = "All words in the English language can be classified as one of the eight different parts of speech.";
print_r(stopWords($text, $stopwords));
我在cmd上的python中收到错误: IndentationError:unindent与任何外部缩进级别都不匹配 Plz弄清楚我做错了什么,并在python
中“替换”答案 0 :(得分:1)
for
应该缩进,当你编写它时,它似乎不在函数中。此外,最后一次返回不与for或函数对齐。
正确的缩进应如下所示:
def stopWords(text, stopwords):
stopwords = map(to_lower(x),stopwords)
pattern = '/[0-9\W]/'
text = re.sub(pattern, ',', text)
text_array = text.partition(',');
text_array = map(to_lower(x), text_array);
keywords = []
for term in text_array:
if(term in stopwords):
keywords.append(term)
return filter(None, keywords)