-2

I am trying to take words from stopwords.txt file and append them as string in python list.

stopwords.txt

  a
  about
  above
  after
  again
  against
  all
  am
  an
  and
  any
  are
  aren't
  as
  at
  be
  because
  been
  before
  being

My Code :

    stopword = open("stopwords.txt", "r")
    stopwords = []
    for word in stopword:
        stopwords.append(word)

List stopwords output:

    ['a\n',
     'about\n',
     'above\n',
     'after\n',
     'again\n',
     'against\n',
     'all\n',
     'am\n',
     'an\n',
     'and\n',
     'any\n',
     'are\n',
     "aren't\n",
     'as\n',
     'at\n',
     'be\n',
     'because\n',
     'been\n',
     'before\n',
     'being\n']

Desired Output :

    ['a',
     'about',
     'above',
     'after',
     'again',
     'against',
     'all',
     'am',
     'an',
     'and',
     'any',
     'are',
     "aren't",
     'as',
     'at',
     'be',
     'because',
     'been',
     'before',
     'being']

Is there any method to transpose stopword so that it eliminate '\n' character or any method at all to reach the desire output?

Mihir
  • 73
  • 1
  • 10
  • 1
    Possible duplicate of [Reading a file without newlines](https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines) – Chris_Rands Jul 23 '18 at 14:03

2 Answers2

1

Instead of

stopwords.append(word)

do

stopwords.append(word.strip())

The string.strip() method strips whitespace of any kind (spaces, tabs, newlines, etc.) from the start and end of the string. You can give an argument to the function in order to strip a specific string or set of characters, or use lstrip() or rstrip() to only strip the front or back of the string, but for this case just strip() should suffice.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

You can use the .strip() method. It removes all occurrences of the character passed as an argument from a string:

stopword = open("stopwords.txt", "r")
stopwords = []
for word in stopword:
    stopwords.append(word.strip("\n"))
Mr.Zeus
  • 424
  • 8
  • 25