1. ภาพรวม

Natural Language API ช่วยให้คุณดึงข้อมูลจากข้อความแบบไม่มีโครงสร้างได้โดยใช้แมชชีนเลิร์นนิงของ Google ในบทแนะนำนี้ คุณจะมุ่งเน้นที่การใช้ไลบรารีของไคลเอ็นต์ Python
สิ่งที่คุณจะได้เรียนรู้
- วิธีตั้งค่าสภาพแวดล้อม
- วิธีวิเคราะห์ความรู้สึก
- วิธีวิเคราะห์เอนทิตี
- วิธีวิเคราะห์ไวยากรณ์
- วิธีแยกประเภทเนื้อหา
- วิธีดำเนินการกลั่นกรองข้อความ
สิ่งที่คุณต้องมี
แบบสำรวจ
คุณจะใช้บทแนะนำนี้อย่างไร
คุณจะให้คะแนนประสบการณ์การใช้งาน Python เท่าใด
คุณจะให้คะแนนประสบการณ์การใช้งานบริการของ Google Cloud เท่าไร
2. การตั้งค่าและข้อกำหนด
การตั้งค่าสภาพแวดล้อมแบบเรียนรู้ด้วยตนเอง
- ลงชื่อเข้าใช้ Google Cloud Console แล้วสร้างโปรเจ็กต์ใหม่หรือใช้โปรเจ็กต์ที่มีอยู่ซ้ำ หากยังไม่มีบัญชี Gmail หรือ Google Workspace คุณต้องสร้างบัญชี



- ชื่อโปรเจ็กต์คือชื่อที่แสดงสำหรับผู้เข้าร่วมโปรเจ็กต์นี้ ซึ่งเป็นสตริงอักขระที่ Google APIs ไม่ได้ใช้ คุณอัปเดตได้ทุกเมื่อ
- รหัสโปรเจ็กต์จะไม่ซ้ำกันในโปรเจ็กต์ Google Cloud ทั้งหมดและเปลี่ยนแปลงไม่ได้ (เปลี่ยนไม่ได้หลังจากตั้งค่าแล้ว) Cloud Console จะสร้างสตริงที่ไม่ซ้ำกันโดยอัตโนมัติ ซึ่งโดยปกติแล้วคุณไม่จำเป็นต้องสนใจว่าสตริงนั้นคืออะไร ใน Codelab ส่วนใหญ่ คุณจะต้องอ้างอิงรหัสโปรเจ็กต์ (โดยทั่วไปจะระบุเป็น
PROJECT_ID) หากไม่ชอบรหัสที่สร้างขึ้น คุณอาจสร้างรหัสแบบสุ่มอีกรหัสหนึ่งได้ หรือคุณอาจลองใช้ชื่อของคุณเองและดูว่ามีชื่อนั้นหรือไม่ คุณจะเปลี่ยนแปลงรหัสนี้หลังจากขั้นตอนนี้ไม่ได้ และรหัสจะคงอยู่ตลอดระยะเวลาของโปรเจ็กต์ - โปรดทราบว่ายังมีค่าที่ 3 ซึ่งคือหมายเลขโปรเจ็กต์ที่ API บางตัวใช้ ดูข้อมูลเพิ่มเติมเกี่ยวกับค่าทั้ง 3 นี้ได้ในเอกสารประกอบ
- จากนั้นคุณจะต้องเปิดใช้การเรียกเก็บเงินใน Cloud Console เพื่อใช้ทรัพยากร/API ของ Cloud การทำตาม Codelab นี้จะไม่มีค่าใช้จ่ายมากนัก หรืออาจไม่มีค่าใช้จ่ายเลย หากต้องการปิดทรัพยากรเพื่อหลีกเลี่ยงการเรียกเก็บเงินนอกเหนือจากบทแนะนำนี้ คุณสามารถลบทรัพยากรที่สร้างขึ้นหรือลบโปรเจ็กต์ได้ ผู้ใช้ Google Cloud รายใหม่มีสิทธิ์เข้าร่วมโปรแกรมช่วงทดลองใช้ฟรีมูลค่า$300 USD
เริ่มต้น Cloud Shell
แม้ว่าคุณจะใช้งาน Google Cloud จากแล็ปท็อประยะไกลได้ แต่ใน Codelab นี้คุณจะใช้ Cloud Shell ซึ่งเป็นสภาพแวดล้อมบรรทัดคำสั่งที่ทำงานในระบบคลาวด์
เปิดใช้งาน Cloud Shell
- จาก Cloud Console ให้คลิกเปิดใช้งาน Cloud Shell


หากคุณเริ่มใช้ Cloud Shell เป็นครั้งแรก คุณจะเห็นหน้าจอระดับกลางที่อธิบายว่า Cloud Shell คืออะไร หากเห็นหน้าจอระดับกลาง ให้คลิกต่อไป

การจัดสรรและเชื่อมต่อกับ Cloud Shell จะใช้เวลาไม่นาน

เครื่องเสมือนนี้โหลดเครื่องมือพัฒนาซอฟต์แวร์ทั้งหมดที่จำเป็นไว้แล้ว โดยมีไดเรกทอรีหลักแบบถาวรขนาด 5 GB และทำงานใน Google Cloud ซึ่งช่วยเพิ่มประสิทธิภาพเครือข่ายและการตรวจสอบสิทธิ์ได้อย่างมาก คุณสามารถทำงานส่วนใหญ่หรือทั้งหมดในโค้ดแล็บนี้ได้ด้วยเบราว์เซอร์
เมื่อเชื่อมต่อกับ Cloud Shell แล้ว คุณควรเห็นว่าคุณได้รับการตรวจสอบสิทธิ์และระบบได้ตั้งค่าโปรเจ็กต์เป็นรหัสโปรเจ็กต์ของคุณ
- เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อยืนยันว่าคุณได้รับการตรวจสอบสิทธิ์แล้ว
gcloud auth list
เอาต์พุตของคำสั่ง
Credentialed Accounts
ACTIVE ACCOUNT
* <my_account>@<my_domain.com>
To set the active account, run:
$ gcloud config set account `ACCOUNT`
- เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อยืนยันว่าคำสั่ง gcloud รู้จักโปรเจ็กต์ของคุณ
gcloud config list project
เอาต์พุตของคำสั่ง
[core] project = <PROJECT_ID>
หากไม่ได้ตั้งค่าไว้ คุณตั้งค่าได้ด้วยคำสั่งนี้
gcloud config set project <PROJECT_ID>
เอาต์พุตของคำสั่ง
Updated property [core/project].
3. การตั้งค่าสภาพแวดล้อม
ก่อนที่จะเริ่มใช้ Natural Language API ได้ ให้เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อเปิดใช้ API
gcloud services enable language.googleapis.com
คุณควรเห็นข้อความคล้ายกับข้อความต่อไปนี้
Operation "operations/..." finished successfully.
ตอนนี้คุณใช้ Natural Language API ได้แล้ว
ไปที่ไดเรกทอรีหลักโดยใช้คำสั่งต่อไปนี้
cd ~
สร้างสภาพแวดล้อมเสมือนของ Python เพื่อแยกการอ้างอิง
virtualenv venv-language
เปิดใช้งานสภาพแวดล้อมเสมือน
source venv-language/bin/activate
ติดตั้ง IPython, Pandas และไลบรารีของไคลเอ็นต์ Natural Language API โดยทำดังนี้
pip install ipython pandas tabulate google-cloud-language
คุณควรเห็นข้อความคล้ายกับข้อความต่อไปนี้
... Installing collected packages: ... pandas ... ipython ... google-cloud-language Successfully installed ... google-cloud-language-2.11.0 ...
ตอนนี้คุณก็พร้อมใช้ไลบรารีของไคลเอ็นต์ Natural Language API แล้ว
ในขั้นตอนถัดไป คุณจะใช้ตัวแปล Python แบบอินเทอร์แอกทีฟที่ชื่อ IPython ซึ่งคุณติดตั้งไว้ในขั้นตอนก่อนหน้า เริ่มเซสชันโดยเรียกใช้ ipython ใน Cloud Shell
ipython
คุณควรเห็นข้อความคล้ายกับข้อความต่อไปนี้
Python 3.9.2 (default, Feb 28 2021, 17:03:44) Type 'copyright', 'credits' or 'license' for more information IPython 8.15.0 -- An enhanced Interactive Python. Type '?' for help. In [1]:
4. การวิเคราะห์ความเห็น
การวิเคราะห์ความรู้สึกจะตรวจสอบข้อความที่ระบุและระบุความคิดเห็นทางอารมณ์ที่โดดเด่นภายในข้อความ โดยเฉพาะอย่างยิ่งเพื่อพิจารณาความรู้สึกที่แสดงออกว่าเป็นบวก ลบ หรือเป็นกลาง ทั้งในระดับประโยคและระดับเอกสาร โดยจะดำเนินการด้วยเมธอด analyze_sentiment ซึ่งจะแสดงผล AnalyzeSentimentResponse
คัดลอกโค้ดต่อไปนี้ลงในเซสชัน IPython
from google.cloud import language
def analyze_text_sentiment(text: str) -> language.AnalyzeSentimentResponse:
client = language.LanguageServiceClient()
document = language.Document(
content=text,
type_=language.Document.Type.PLAIN_TEXT,
)
return client.analyze_sentiment(document=document)
def show_text_sentiment(response: language.AnalyzeSentimentResponse):
import pandas as pd
columns = ["score", "sentence"]
data = [(s.sentiment.score, s.text.content) for s in response.sentences]
df_sentence = pd.DataFrame(columns=columns, data=data)
sentiment = response.document_sentiment
columns = ["score", "magnitude", "language"]
data = [(sentiment.score, sentiment.magnitude, response.language)]
df_document = pd.DataFrame(columns=columns, data=data)
format_args = dict(index=False, tablefmt="presto", floatfmt="+.1f")
print(f"At sentence level:\n{df_sentence.to_markdown(**format_args)}")
print()
print(f"At document level:\n{df_document.to_markdown(**format_args)}")
ทำการวิเคราะห์
# Input
text = """
Python is a very readable language, which makes it easy to understand and maintain code.
It's simple, very flexible, easy to learn, and suitable for a wide variety of tasks.
One disadvantage is its speed: it's not as fast as some other programming languages.
"""
# Send a request to the API
analyze_sentiment_response = analyze_text_sentiment(text)
# Show the results
show_text_sentiment(analyze_sentiment_response)
คุณควรเห็นเอาต์พุตดังต่อไปนี้
At sentence level:
score | sentence
---------+------------------------------------------------------------------------------------------
+0.8 | Python is a very readable language, which makes it easy to understand and maintain code.
+0.9 | It's simple, very flexible, easy to learn, and suitable for a wide variety of tasks.
-0.4 | One disadvantage is its speed: it's not as fast as some other programming languages.
At document level:
score | magnitude | language
---------+-------------+------------
+0.4 | +2.2 | en
โปรดใช้เวลาสักครู่เพื่อทดสอบประโยคของคุณเอง
สรุป
ในขั้นตอนนี้ คุณสามารถวิเคราะห์ความรู้สึกในสตริงข้อความได้
5. การวิเคราะห์เอนทิตี
การวิเคราะห์เอนทิตีจะตรวจสอบข้อความที่ระบุเพื่อหาเอนทิตีที่รู้จัก (คำนามเฉพาะ เช่น บุคคลสาธารณะ สถานที่สำคัญ ฯลฯ) และแสดงข้อมูลเกี่ยวกับเอนทิตีเหล่านั้น โดยจะดำเนินการด้วยเมธอด analyze_entities ซึ่งจะแสดงผล AnalyzeEntitiesResponse
คัดลอกโค้ดต่อไปนี้ลงในเซสชัน IPython
from google.cloud import language
def analyze_text_entities(text: str) -> language.AnalyzeEntitiesResponse:
client = language.LanguageServiceClient()
document = language.Document(
content=text,
type_=language.Document.Type.PLAIN_TEXT,
)
return client.analyze_entities(document=document)
def show_text_entities(response: language.AnalyzeEntitiesResponse):
import pandas as pd
columns = ("name", "type", "salience", "mid", "wikipedia_url")
data = (
(
entity.name,
entity.type_.name,
entity.salience,
entity.metadata.get("mid", ""),
entity.metadata.get("wikipedia_url", ""),
)
for entity in response.entities
)
df = pd.DataFrame(columns=columns, data=data)
print(df.to_markdown(index=False, tablefmt="presto", floatfmt=".0%"))
ทำการวิเคราะห์
# Input
text = """Guido van Rossum is best known as the creator of Python,
which he named after the Monty Python comedy troupe.
He was born in Haarlem, Netherlands.
"""
# Send a request to the API
analyze_entities_response = analyze_text_entities(text)
# Show the results
show_text_entities(analyze_entities_response)
คุณควรเห็นเอาต์พุตดังต่อไปนี้
name | type | salience | mid | wikipedia_url ------------------+--------------+------------+-----------+------------------------------------------------------------- Guido van Rossum | PERSON | 50% | /m/01h05c | https://en.wikipedia.org/wiki/Guido_van_Rossum Python | ORGANIZATION | 38% | /m/05z1_ | https://en.wikipedia.org/wiki/Python_(programming_language) creator | PERSON | 5% | | Monty Python | PERSON | 3% | /m/04sd0 | https://en.wikipedia.org/wiki/Monty_Python comedy troupe | PERSON | 2% | | Haarlem | LOCATION | 1% | /m/0h095 | https://en.wikipedia.org/wiki/Haarlem Netherlands | LOCATION | 1% | /m/059j2 | https://en.wikipedia.org/wiki/Netherlands
ลองใช้เวลาสักครู่เพื่อทดสอบประโยคของคุณเองที่กล่าวถึงเอนทิตีอื่นๆ
สรุป
ในขั้นตอนนี้ คุณจะวิเคราะห์เอนทิตีได้
6. การวิเคราะห์ไวยากรณ์
การวิเคราะห์ไวยากรณ์จะดึงข้อมูลทางภาษาศาสตร์ออกมา โดยแบ่งข้อความที่กำหนดออกเป็นชุดประโยคและโทเค็น (โดยทั่วไปจะอิงตามขอบเขตของคำ) เพื่อให้วิเคราะห์โทเค็นเหล่านั้นเพิ่มเติมได้ โดยจะดำเนินการด้วยเมธอด analyze_syntax ซึ่งจะแสดงผล AnalyzeSyntaxResponse
คัดลอกโค้ดต่อไปนี้ลงในเซสชัน IPython
from typing import Optional
from google.cloud import language
def analyze_text_syntax(text: str) -> language.AnalyzeSyntaxResponse:
client = language.LanguageServiceClient()
document = language.Document(
content=text,
type_=language.Document.Type.PLAIN_TEXT,
)
return client.analyze_syntax(document=document)
def get_token_info(token: Optional[language.Token]) -> list[str]:
parts = [
"tag",
"aspect",
"case",
"form",
"gender",
"mood",
"number",
"person",
"proper",
"reciprocity",
"tense",
"voice",
]
if not token:
return ["token", "lemma"] + parts
text = token.text.content
lemma = token.lemma if token.lemma != token.text.content else ""
info = [text, lemma]
for part in parts:
pos = token.part_of_speech
info.append(getattr(pos, part).name if part in pos else "")
return info
def show_text_syntax(response: language.AnalyzeSyntaxResponse):
import pandas as pd
tokens = len(response.tokens)
sentences = len(response.sentences)
columns = get_token_info(None)
data = (get_token_info(token) for token in response.tokens)
df = pd.DataFrame(columns=columns, data=data)
# Remove empty columns
empty_columns = [col for col in df if df[col].eq("").all()]
df.drop(empty_columns, axis=1, inplace=True)
print(f"Analyzed {tokens} token(s) from {sentences} sentence(s):")
print(df.to_markdown(index=False, tablefmt="presto"))
ทำการวิเคราะห์
# Input
text = """Guido van Rossum is best known as the creator of Python.
He was born in Haarlem, Netherlands.
"""
# Send a request to the API
analyze_syntax_response = analyze_text_syntax(text)
# Show the results
show_text_syntax(analyze_syntax_response)
คุณควรเห็นเอาต์พุตดังต่อไปนี้
Analyzed 20 token(s) from 2 sentence(s): token | lemma | tag | case | gender | mood | number | person | proper | tense | voice -------------+---------+-------+------------+-----------+------------+----------+----------+----------+---------+--------- Guido | | NOUN | | | | SINGULAR | | PROPER | | van | | NOUN | | | | SINGULAR | | PROPER | | Rossum | | NOUN | | | | SINGULAR | | PROPER | | is | be | VERB | | | INDICATIVE | SINGULAR | THIRD | | PRESENT | best | well | ADV | | | | | | | | known | know | VERB | | | | | | | PAST | as | | ADP | | | | | | | | the | | DET | | | | | | | | creator | | NOUN | | | | SINGULAR | | | | of | | ADP | | | | | | | | Python | | NOUN | | | | SINGULAR | | PROPER | | . | | PUNCT | | | | | | | | He | | PRON | NOMINATIVE | MASCULINE | | SINGULAR | THIRD | | | was | be | VERB | | | INDICATIVE | SINGULAR | THIRD | | PAST | born | bear | VERB | | | | | | | PAST | PASSIVE in | | ADP | | | | | | | | Haarlem | | NOUN | | | | SINGULAR | | PROPER | | , | | PUNCT | | | | | | | | Netherlands | | NOUN | | | | SINGULAR | | PROPER | | . | | PUNCT | | | | | | | |
ลองใช้เวลาสักครู่เพื่อทดสอบประโยคของคุณเองด้วยโครงสร้างทางไวยากรณ์อื่นๆ
หากเจาะลึกข้อมูลเชิงลึกของคำตอบ คุณจะเห็นความสัมพันธ์ระหว่างโทเค็นด้วย ต่อไปนี้คือการตีความภาพที่แสดงการวิเคราะห์ไวยากรณ์ที่สมบูรณ์สำหรับตัวอย่างนี้ ซึ่งเป็นภาพหน้าจอจากการสาธิตภาษาธรรมชาติออนไลน์

สรุป
ในขั้นตอนนี้ คุณสามารถวิเคราะห์ไวยากรณ์ได้
7. การแยกประเภทเนื้อหา
การแยกประเภทเนื้อหาจะวิเคราะห์เอกสารและแสดงรายการหมวดหมู่เนื้อหาที่ใช้กับข้อความที่พบในเอกสาร โดยจะดำเนินการด้วยเมธอด classify_text ซึ่งจะแสดงผล ClassifyTextResponse
คัดลอกโค้ดต่อไปนี้ลงในเซสชัน IPython
from google.cloud import language
def classify_text(text: str) -> language.ClassifyTextResponse:
client = language.LanguageServiceClient()
document = language.Document(
content=text,
type_=language.Document.Type.PLAIN_TEXT,
)
return client.classify_text(document=document)
def show_text_classification(text: str, response: language.ClassifyTextResponse):
import pandas as pd
columns = ["category", "confidence"]
data = ((category.name, category.confidence) for category in response.categories)
df = pd.DataFrame(columns=columns, data=data)
print(f"Text analyzed:\n{text}")
print(df.to_markdown(index=False, tablefmt="presto", floatfmt=".0%"))
ทำการวิเคราะห์
# Input
text = """Python is an interpreted, high-level, general-purpose programming language.
Created by Guido van Rossum and first released in 1991, Python's design philosophy
emphasizes code readability with its notable use of significant whitespace.
"""
# Send a request to the API
classify_text_response = classify_text(text)
# Show the results
show_text_classification(text, classify_text_response)
คุณควรเห็นเอาต์พุตดังต่อไปนี้
Text analyzed: Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. category | confidence --------------------------------------+-------------- /Computers & Electronics/Programming | 99% /Science/Computer Science | 99%
ลองทดสอบประโยคของคุณเองที่เกี่ยวข้องกับหมวดหมู่อื่นๆ โปรดทราบว่าคุณต้องระบุบล็อกข้อความ (เอกสาร) ที่มีโทเค็น (คำและเครื่องหมายวรรคตอน) อย่างน้อย 20 รายการ
สรุป
ในขั้นตอนนี้ คุณสามารถทำการจัดประเภทเนื้อหาได้แล้ว
8. การกลั่นกรองข้อความ
การกลั่นกรองข้อความซึ่งขับเคลื่อนโดยโมเดลพื้นฐาน PaLM 2 รุ่นล่าสุดของ Google จะระบุเนื้อหาที่เป็นอันตรายได้หลากหลายประเภท รวมถึงวาจาสร้างความเกลียดชัง การกลั่นแกล้ง และการคุกคามทางเพศ โดยจะดำเนินการด้วยเมธอด moderate_text ซึ่งจะแสดงผล ModerateTextResponse
คัดลอกโค้ดต่อไปนี้ลงในเซสชัน IPython
from google.cloud import language
def moderate_text(text: str) -> language.ModerateTextResponse:
client = language.LanguageServiceClient()
document = language.Document(
content=text,
type_=language.Document.Type.PLAIN_TEXT,
)
return client.moderate_text(document=document)
def show_text_moderation(text: str, response: language.ModerateTextResponse):
import pandas as pd
def confidence(category: language.ClassificationCategory) -> float:
return category.confidence
columns = ["category", "confidence"]
categories = sorted(response.moderation_categories, key=confidence, reverse=True)
data = ((category.name, category.confidence) for category in categories)
df = pd.DataFrame(columns=columns, data=data)
print(f"Text analyzed:\n{text}")
print(df.to_markdown(index=False, tablefmt="presto", floatfmt=".0%"))
ทำการวิเคราะห์
# Input
text = """I have to read Ulysses by James Joyce.
I'm a little over halfway through and I hate it.
What a pile of garbage!
"""
# Send a request to the API
response = moderate_text(text)
# Show the results
show_text_moderation(text, response)
คุณควรเห็นเอาต์พุตดังต่อไปนี้
Text analyzed: I have to read Ulysses by James Joyce. I'm a little over halfway through and I hate it. What a pile of garbage! category | confidence -----------------------+-------------- Toxic | 67% Insult | 58% Profanity | 53% Violent | 48% Illicit Drugs | 29% Religion & Belief | 27% Politics | 22% Death, Harm & Tragedy | 21% Finance | 18% Derogatory | 14% Firearms & Weapons | 11% Health | 10% Legal | 10% War & Conflict | 7% Public Safety | 5% Sexual | 4%
โปรดใช้เวลาสักครู่เพื่อทดสอบประโยคของคุณเอง
สรุป
ในขั้นตอนนี้ คุณสามารถดำเนินการกลั่นกรองข้อความได้แล้ว
9. ยินดีด้วย

คุณได้เรียนรู้วิธีใช้ Natural Language API โดยใช้ Python แล้ว
ล้างข้อมูล
หากต้องการล้างข้อมูลสภาพแวดล้อมในการพัฒนา ให้ทำดังนี้จาก Cloud Shell
- หากยังอยู่ในเซสชัน IPython ให้กลับไปที่เชลล์โดยทำดังนี้
exit - หยุดใช้สภาพแวดล้อมเสมือนของ Python:
deactivate - ลบโฟลเดอร์สภาพแวดล้อมเสมือน
cd ~ ; rm -rf ./venv-language
หากต้องการลบโปรเจ็กต์ Google Cloud ให้ทำดังนี้จาก Cloud Shell
- ดึงรหัสโปรเจ็กต์ปัจจุบัน:
PROJECT_ID=$(gcloud config get-value core/project) - โปรดตรวจสอบว่าโปรเจ็กต์ที่คุณต้องการลบคือ
echo $PROJECT_ID - ลบโปรเจ็กต์:
gcloud projects delete $PROJECT_ID
ดูข้อมูลเพิ่มเติม
- ทดสอบเดโมในเบราว์เซอร์ที่ https://cloud.google.com/natural-language#natural-language-api-demo
- เอกสารประกอบเกี่ยวกับ Natural Language: https://cloud.google.com/natural-language/docs
- Python ใน Google Cloud: https://cloud.google.com/python
- ไลบรารีของไคลเอ็นต์ Cloud สำหรับ Python: https://github.com/googleapis/google-cloud-python
ใบอนุญาต
ผลงานนี้ได้รับอนุญาตภายใต้สัญญาอนุญาตครีเอทีฟคอมมอนส์สำหรับยอมรับสิทธิของผู้สร้าง (Creative Commons Attribution License) 2.0 แบบทั่วไป