'Python excel append data
I am trying to append stemmed words into the rows in column L in excel, however I want it to append the values one by one in the for loop for each cell and then move on to the next, if I do ws[L1]= stemmeddata, it will only input the last word into the cell.
from hashlib import new
import pandas as pd
from string import punctuation
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem import SnowballStemmer
pst=PorterStemmer()
wb = load_workbook('report.xlsx')
ws = wb.active
sbst=SnowballStemmer('english')
df = pd.read_excel('report.xlsx')
for row in range(2,10):
for col in range(10,11):
char = get_column_letter(col)
data = ws[char + str(row)].value
data = data.lower()
data = data.replace('-',"").replace('"',"").replace(':',"").replace('/',"").replace(',',"")
new = word_tokenize(data)
for w in new:
stemmeddata = pst.stem(w)
#print(stemmeddata)
for i in range(2,20):
ws['L'+ str(i)] = stemmeddata
wb.save('stem.xlsx')
Solution 1:[1]
# other codes
df = pd.read_excel('report.xlsx')
stemmeddata = "" # Add this
for row in range(2,10):
# other codes
for w in new:
stemmeddata += pst.stem(w) # Add plus sign, instead of just = sign
# other codes
You need to initialize stemmeddata (better variable name is stemmed_data) and concatenate new data inside the loop. Alternative concatenation is:
stemmeddata = stemmeddata + pst.stem(w)
Without initializing, stemmeddata gets the last data you've assigned to it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alvin Cruz |
