from ironpdf import *
# Instantiate Renderer
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
# Export to a file or Stream
pdf.SaveAs("output.pdf")
# Advanced Example with HTML Assets
# Load external html assets: Images, CSS and JavaScript.
# An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
fastText Python (Comment ça fonctionne : Un guide pour les développeurs)
Publié mars 5, 2025
Partager:
Introduction à FastText
FastTextest une bibliothèque Python initialement développée par le laboratoire de recherche en intelligence artificielle de Facebook(FAIR)qui offre une classification de texte efficace et un apprentissage de représentation de mots. Il offre une approche innovante de la représentation des mots, en répondant à certaines des limitations des modèles précédents comme Word2Vec. Sa capacité à comprendre les vecteurs ou éléments sous-mots et à gérer divers défis linguistiques en fait un outil puissant dans la panoplie NLP. FastText est compatible avec les distributions modernes de macOS et Linux. Dans cet article, nous allons apprendre à connaître le package FastText pour Python ainsi qu'une bibliothèque polyvalente de génération de PDF,IronPDF deIron Software.
Caractéristiques
Modèle de Représentation des Mots :
Apprenez à calculer les vecteurs de mots, utilisez fasttext.train_unsupervised avec soit le modèle skip-gram, soit le modèle CBOW pour une utilisation de mémoire faible :
import fasttext
model = fasttext.train_unsupervised('data.txt', model='skipgram')
# data.txt is the training file
import fasttext
model = fasttext.train_unsupervised('data.txt', model='skipgram')
# data.txt is the training file
import fasttext model = fasttext.train_unsupervised( 'data.txt', model='skipgram')
#data.txt is the training file
$vbLabelText $csharpLabel
Récupérer les vecteurs de mots :
print(model.words) # List of words in the dictionary
print(model['king']) # Vector for the word 'king'
print(model.words) # List of words in the dictionary
print(model['king']) # Vector for the word 'king'
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.words) # List @of words in the dictionary print(model['king']) # Vector for the word 'king'
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model.save_model("model_filename.bin") loaded_model = fasttext.load_model("model_filename.bin")
$vbLabelText $csharpLabel
Modèle de classification de texte :
Entraînez des classificateurs de texte supervisés en utilisant fasttext.train_supervised ou utilisez un modèle préalablement entraîné :
model = fasttext.train_supervised('data.train.txt')
model = fasttext.train_supervised('data.train.txt')
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model = fasttext.train_supervised('data.train.txt')
$vbLabelText $csharpLabel
Évaluer le modèle dans la fenêtre de contexte :
print(model.test('data.test.txt')) # Precision and recall
print(model.test('data.test.txt')) # Precision and recall
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.test('data.test.txt')) # Precision @and recall
$vbLabelText $csharpLabel
Prédire les étiquettes pour un texte spécifique :
print(model.predict("Which baking dish is best for banana bread?"))
print(model.predict("Which baking dish is best for banana bread?"))
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.predict("Which baking dish is best for banana bread?"))
$vbLabelText $csharpLabel
Exemples de codes
Le code démontre comment entraîner un modèle de classification de texte en utilisant FastText :
import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
"__label__positive I love this!",
"__label__negative This movie is terrible.",
"__label__positive Great job!",
"__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
for item in train_data:
f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
"I like it.",
"Not good.",
"Awesome!"
]
for text in texts:
print(f"Input text: '{text}'")
print("Predicted label:", model.predict(text))
print()
import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
"__label__positive I love this!",
"__label__negative This movie is terrible.",
"__label__positive Great job!",
"__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
for item in train_data:
f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
"I like it.",
"Not good.",
"Awesome!"
]
for text in texts:
print(f"Input text: '{text}'")
print("Predicted label:", model.predict(text))
print()
#Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print()
$vbLabelText $csharpLabel
Explication de la sortie
Formation : L'exemple entraîne un modèle FastText en utilisant un petit ensemble de données(train_data). Chaque entrée dans train_data commence par une étiquette suivie d'une étiquette(positif, négatif, neutre)et le texte correspondant.
Prédiction : Après l'entraînement, le modèle prédit les étiquettes(positif, négatif, neutre)pour les nouveaux textes d'entrée(textes). Chaque texte est classé dans l'une des étiquettes en fonction du modèle entraîné.
Sortie
Présentation d'IronPDF
IronPDF est une bibliothèque Python robuste conçue pour créer, éditer et signer numériquement des documents PDF en utilisant HTML, CSS, des images et JavaScript. Il excelle en termes de performances tout en conservant une empreinte mémoire minimale. Les principales caractéristiques sont les suivantes :
Conversion HTML en PDF : Convertissez des fichiers HTML, des chaînes HTML et des URL en documents PDF, avec la capacité de rendre des pages web en utilisant le moteur de rendu PDF de Chrome.
Prise en charge multiplateforme : Compatible avec Python 3+ sur Windows, Mac, Linux et diverses plateformes cloud. IronPDF est également disponible pour les environnements .NET, Java, Python et Node.js.
Édition et Signature : Personnalisez les propriétés des PDF, renforcez la sécurité avec des mots de passe et des autorisations, et appliquez des signatures numériques aux documents.
Templates de page et paramètres : Personnalisez les PDFs avec des en-têtes, pieds de page, numéros de page, marges ajustables, tailles de papier personnalisées et mises en page adaptatives.
Conformité aux normes : Garantit le respect des normes PDF telles que PDF/A et PDF/UA, prend en charge le codage des caractères UTF-8 et gère de manière transparente les ressources telles que les images, les feuilles de style CSS et les polices.
Installation
pip install fastText
pip install fastText
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText
$vbLabelText $csharpLabel
Générez des documents PDF en utilisant IronPDF et FastText
Conditions préalables
Assurez-vous que Visual Studio Code est installé en tant qu'éditeur de code
La version 3 de Python est installée
Pour commencer, créons un fichier Python pour ajouter nos scripts.
Ouvrez Visual Studio Code et créez un fichier, fastTextDemo.py.
Installer les bibliothèques nécessaires :
pip install fastText
pip install ironpdf
pip install fastText
pip install ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText pip install ironpdf
$vbLabelText $csharpLabel
Ajoutez ensuite le code ci-dessous pour démontrer l'utilisation des packages Python IronPDF et FastText.
import fasttext
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words, rare words and out of vocabulary words
train_data = [
"__label__positive I love this!",
"__label__negative This movie is terrible.",
"__label__positive Great job!",
"__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
for item in train_data:
f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
"I like it.",
"Not good.",
"Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
print(data)
content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
print(f"Input text: '{text}'")
print("Predicted label:", model.predict(text))
print()
content += f"<p>----------------------------------------------</p>"
content += f"<p>Input text: '{text}</p>"
content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
import fasttext
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words, rare words and out of vocabulary words
train_data = [
"__label__positive I love this!",
"__label__negative This movie is terrible.",
"__label__positive Great job!",
"__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
for item in train_data:
f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
"I like it.",
"Not good.",
"Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
print(data)
content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
print(f"Input text: '{text}'")
print("Predicted label:", model.predict(text))
print()
content += f"<p>----------------------------------------------</p>"
content += f"<p>Input text: '{text}</p>"
content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
#Apply your license key
#Create a PDF from a HTML string using Python
#Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words, rare words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
#Export to a file or Stream
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext from ironpdf import * License.LicenseKey = "key" content = "<h1>Awesome Iron PDF with Fasttext</h1>" train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] content += "<h2>Training data</h2>" for data in train_data: print(data) content += f"<p>{data}</p>" content += "<h2>Train a supervised model</h2>" content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>" content += "<h2>Testing the model</h2>" for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print() content += f"<p>----------------------------------------------</p>" content += f"<p>Input text: '{text}</p>" content += f"<p>Predicted label:{model.predict(text)}</p>" pdf = renderer.RenderHtmlAsPdf(content) pdf.SaveAs("DemoIronPDF-FastText.pdf")
$vbLabelText $csharpLabel
Sortie
PDF (EN ANGLAIS)
Licence d'IronPDF
IronPDF fonctionne avec une clé de licence pour Python. IronPDF pour Python offre un service deessai gratuitclé de licence pour permettre aux utilisateurs de commencer gratuitement.
Placez la clé de licence au début du script avant d'utiliser lePaquet IronPDF:
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText $csharpLabel
Conclusion
FastText est une bibliothèque légère et efficace pour la représentation et la classification de texte. Il se distingue dans l'apprentissage des embeddings de mots en utilisant des informations sur les sous-mots, en soutenant les tâches de classification de texte avec une grande vitesse et évolutivité, en offrant des modèles pré-entraînés pour plusieurs langues, et en fournissant une interface Python conviviale pour une intégration facile dans les projets. IronPDF est une bibliothèque Python complète pour créer, éditer et afficher des documents PDF de manière programmatique. Il simplifie des tâches telles que la conversion de HTML en PDF, l'ajout de contenu et d'annotations aux PDF, la gestion des propriétés et de la sécurité des documents, et est compatible avec différents systèmes d'exploitation et environnements de programmation. Idéal pour générer et manipuler des PDF au sein d'applications Python de manière efficace.
Ensemble avec les deux bibliothèques, nous pouvons entraîner des modèles de texte et documenter les résultats de sortie au format PDF à des fins d'archivage.
Avant de devenir ingénieur logiciel, Kannapat a obtenu un doctorat en ressources environnementales à l'université d'Hokkaido au Japon. Tout en poursuivant ses études, Kannapat est également devenu membre du Vehicle Robotics Laboratory, qui fait partie du Department of Bioproduction Engineering (département d'ingénierie de la bioproduction). En 2022, il a mis à profit ses compétences en C# pour rejoindre l'équipe d'ingénieurs d'Iron Software, où il se concentre sur IronPDF. Kannapat apprécie son travail car il apprend directement auprès du développeur qui écrit la majeure partie du code utilisé dans IronPDF. Outre l'apprentissage par les pairs, Kannapat apprécie l'aspect social du travail chez Iron Software. Lorsqu'il n'écrit pas de code ou de documentation, Kannapat peut généralement être trouvé en train de jouer sur sa PS5 ou de revoir The Last of Us.
< PRÉCÉDENT Folium Python (Comment ça fonctionne : Un guide pour les développeurs)
SUIVANT > Bottle Python ((Comment ça fonctionne : Un guide pour les développeurs))
Des millions d'ingénieurs dans le monde entier lui font confiance
Réservez une démo en direct gratuite
Réservez une démonstration personnelle de 30 minutes.
Pas de contrat, pas de détails de carte, pas d'engagements.
Voici ce à quoi vous pouvez vous attendre :
Une démonstration en direct de notre produit et de ses principales fonctionnalités
Obtenez des recommandations de fonctionnalités spécifiques au projet
Toutes vos questions trouvent réponse pour vous assurer de disposer de toutes les informations dont vous avez besoin. (Aucune obligation de votre part.)
CHOISIR L'HEURE
VOS INFORMATIONS
Réservez votre gratuit Démonstration en direct
Fiable par plus de 2 millions d'ingénieurs dans le monde entier