将PHP函数转换为Python 3
尝试将PHP函数转换为Python,我是Python方面的新手,这就是我所尝试的 Python->将PHP函数转换为Python 3,php,python,python-3.x,function,Php,Python,Python 3.x,Function,尝试将PHP函数转换为Python,我是Python方面的新手,这就是我所尝试的 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),
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中的错误:
缩进错误:未缩进与任何外部缩进级别不匹配
请找出我做错了什么,python中的“文件”选项应该缩进的
,当您编写它时,它似乎超出了函数的范围。此外,最后一个返回值不与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)
您没有正确指定代码行的用途。与PHP不同,缩进在Python中非常重要。您知道为什么需要在Python中使用缩进吗?您知道文本数组中术语的行:
结束了函数吗?@Matthias不,我不知道,但我有兴趣知道that@Matthias好的,明白了,Python中的空格数(enter)是定义属于一起的事物的方法。在PHP中使用{
和}
,代码的缩进是可选的。在Python中,代码的缩进定义了代码结构。@LovePreetighBatth只要正确缩进函数,它就应该工作