Home > Blockchain >  How to take text from file?
How to take text from file?

Time:05-31

I'm a beginner in Python, and I don't get how to take a text from a file.

I've tried a lot of codes that I found on this forum, but it seems that no one tried to do what I'm trying to do.

It's been 3 days I'm trying to do that and I feel like It's impossible.

Here is the code, I have a file named 1.txt and I'm wondering how to get the content of 1.txt right here : """Text from my file here"""

Is there a way to do that?

Thanks in advance!



def analyze_text_sentiment(text):
   client = language.LanguageServiceClient()
   document = language.Document(content=text, type_=language.Document.Type.PLAIN_TEXT)

   response = client.analyze_sentiment(document=document)

   sentiment = response.document_sentiment
   results = dict(
       text=text,
       score=f"{sentiment.score:.1%}",
       magnitude=f"{sentiment.magnitude:.1%}",
   )
   for k, v in results.items():
       print(f"{k:10}: {v}")

from google.cloud import language


def analyze_text_entities(text):
   client = language.LanguageServiceClient()
   document = language.Document(content=text, type_=language.Document.Type.PLAIN_TEXT)

   response = client.analyze_entities(document=document)

   for entity in response.entities:
       print("=" * 80)
       results = dict(
           name=entity.name,
           type=entity.type_.name,
           salience=f"{entity.salience:.1%}",
           wikipedia_url=entity.metadata.get("wikipedia_url", "-"),
           mid=entity.metadata.get("mid", "-"),
       )
       for k, v in results.items():
           print(f"{k:15}: {v}")
           

text = """Text from my file here"""
analyze_text_sentiment(text)
analyze_text_entities(text)

CodePudding user response:

You just need to open the file and read it. Assuming the 1.txt file is in the same directory you run your python script from:

with open("1.txt") as f:
    text = f.read()

analyze_text_sentiment(text)
analyze_text_entities(text)

The with ... as f context manager implicitly closes the file for us, even if we experience errors inside the block, always use it to read files.

Documentation for open can be found here.

  • Related