На странице обзора приложения-функции я создал на портале новую функцию со следующими настройками:
Я выбрал вкладку «Код + Тест», заменил код функции по умолчанию кодом ниже и сохранил его.
import logging
import azure.functions as func
import json
import re
from collections import Counter
# List of stop words to be ignored
STOPWORDS = set([
'', 'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you',
"you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself',
'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her',
'hers', 'herself', 'it', "it's", 'itself', 'they', 'them',
'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom',
'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was',
'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do',
'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or',
'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with',
'about', 'against', 'between', 'into', 'through', 'during', 'before',
'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out',
'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here',
'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each',
'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not',
'only', 'own', 'same', 'so', 'than', 'too', 'very', 'can', 'will',
'just', "don't", 'should', "should've", 'now', "aren't", "couldn't",
"didn't", "doesn't", "hadn't", "hasn't", "haven't", "isn't", "mightn't", "mustn't",
"needn't", "shan't", "shouldn't", "wasn't", "weren't", "won't", "wouldn't"
])
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
try:
req_body = req.get_json()
if "values" in req_body:
vals = req_body["values"]
res = {"values": []}
for rec in vals:
# Get the record ID and text for this input
record_id = rec['recordId']
text = rec['data'].get('text', '')
# Remove punctuation and numerals, and convert to lowercase
text = re.sub(r'[^A-Za-z\s]', '', text).lower()
# Get an array of words
words = text.split()
# Count instances of non-stopwords
word_counts = Counter(word for word in words if word not in STOPWORDS)
# Get the top 10 most frequent words
top_words = [word for word, count in word_counts.most_common(10)]
# Append result for this record
res["values"].append({
"recordId": record_id,
"data": {
"text": top_words
}
})
return func.HttpResponse(
body=json.dumps(res),
status_code=200,
mimetype = "application/json"
)
else:
return func.HttpResponse(
body=json.dumps({"errors": [{"message": "Invalid input"}]}),
status_code=400,
mimetype = "application/json"
)
except Exception as e:
logging.error(f"Error processing request: {e}")
return func.HttpResponse(
body=json.dumps({"errors": [{"message": str(e)}]}),
status_code=500,
mimetype = "application/json"
)
На панели «Тестирование/Выполнение» я заменяю существующее тело следующим JSON, и при его запуске получаю ошибку 404.
Примечание. Я использовал запрос https POST
.
{
"values": [
{
"recordId": "a1",
"data":
{
"text": "Tiger, tiger burning bright in the darkness of the night.",
"language": "en"
}
},
{
"recordId": "a2",
"data":
{
"text": "The rain in spain stays mainly in the plains! That's where you'll find the rain!",
"language": "en"
}
}
]
}
Однако приведенный ниже код представляет собой схему, которую я должен получить.
{
"values": [
{
"recordId": "a1",
"data": {
"text": [
"tiger",
"burning",
"bright",
"darkness",
"night"
]
},
"errors": null,
"warnings": null
},
{
"recordId": "a2",
"data": {
"text": [
"rain",
"spain",
"stays",
"mainly",
"plains",
"thats",
"youll",
"find"
]
},
"errors": null,
"warnings": null
}
]
}
Сначала создал функцию Python с количеством слов и уровнем функции, как показано ниже:
Первоначально я также получил 404 Not Found, используя ваш код:
Затем я заменил def main(req: func.HttpRequest) -> func.HttpResponse:
на
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route = "wordcount")
def wordcount(req: func.HttpRequest) -> func.HttpResponse:
тогда это сработало для меня:
import logging
import azure.functions as func
import json
import re
from collections import Counter
# List of stop words to be ignored
STOPWORDS = set([
'', 'i', 'me', 'my', 'myself', ---
--------------------------------------//rest same
--------------------------------------
"wouldn't"])
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route = "wordcount")
def wordcount(req: func.HttpRequest) -> func.HttpResponse:
-----------
-----------//rest same
-----------
Большое спасибо за это. У меня это тоже сработало