Количество слов строки в файле Excel с использованием Python - PullRequest
0 голосов
/ 23 октября 2019

У меня есть файл Excel с несколькими столбцами. В одной колонке у меня разные комментарии. Я хочу создать столбец рядом с ним, чтобы найти количество слов в столбцах комментариев, используя код Python. Есть ли возможность.

picture

Ответы [ 2 ]

0 голосов
/ 24 октября 2019
import pandas as pd

df #is your dataframe

counter = [] #future column you want

for string in df.Comments.values: #for each string in your "Comments"
    counter.append(string.count(' ') + 1) #num of spaces + 1

df['num_words'] = counter #add the column
df = df[['num_words', 'Comments']] #change the order of columns

мой df был мой df

и я наконец получил этот df

0 голосов
/ 24 октября 2019

Попробуйте это:

import xlrd
import os
from string import punctuation, translate
from collections import Counter

filename = u'test.xlsx'
sheet_no = 1  # To get the first sheet of the workbook
path = 'C:\Users\myUsername\Directory for Excel files'
punctuation_map = dict((ord(c), u' ') for c in punctuation)

for filename in os.listdir(path):
   if filename.endswith('.xlsx'):
      print filename
      workbook = xlrd.open_workbook(filename)
      sheet = workbook.sheet_by_index(sheet_no)
      values = []
      for row in range(sheet.nrows):
          for col in range(sheet.ncols):
              c = sheet.cell(row, col)
              if c.ctype == xlrd.XL_CELL_TEXT:
                 cv = unicode(c.value)
                 wordlist = cv.translate(punctuation_map).split()
                 values.extend(wordlist)
                 numberWords = Counter(wordlist)
                 print sum(numberWords.values()), ' words for that column'

      count = Counter(values)
      print sum(count.values()), ' total words counted (from all columns)'
...