Доступ к словам по индексу в python - PullRequest
1 голос
/ 14 июля 2020

Я не знаю, возможно ли это, но я пытаюсь получить доступ к словам (не отдельным символам) из разделенной строки по индексам и сохранить их в словаре. Если это не сработает, пожалуйста, есть ли какие-либо другие предложения относительно того, как go получить тот же результат. Это мой код:

def main():
if len(argv) != 2:
    print("usage: python import.py (csv file)")
    exit(0)


db = SQL("sqlite:///students.db")

file = open(argv[2], 'r')
csv_file = DictReader(file)

for row in csv_file:
    names = row['name']
    for i in names:
        word = i.split()

  # what the csv looks like
  name,house,birth
  Adelaide Murton,Slytherin,1982
  Adrian Pucey,Slytherin,1977
  Anthony Goldstein,Ravenclaw,1980
   
  # what i want it to look like
  first name,middle name,last name,house,birth
  Adelaide,None,Murton,Slytherin,1982
  Adrian,None,Pucey,Slytherin,1977
  Anthony,None,Goldstein,Ravenclaw,1980 
       

Ответы [ 3 ]

0 голосов
/ 14 июля 2020
sentence = 'This is an example'  # string: 'This is an example'
words = sentence.split()         # list of strings: ['This', 'is', 'an', 'example']

На этом этапе вы можете получить конкретное c слово, вызвав его индекс, или l oop через них, например for word in words:.

Я не уверен насчет SQL часть вашего кода, но похоже, что вы уже перебираете слова, когда делаете for i in names:.

0 голосов
/ 14 июля 2020

Вы можете попробовать с помощью этого кода

def create_word_index(filenames, rare_word_flag=False):
    word_index, word_count, single_words = {}, 0, []  # original : word_count = 0

    ## Handle word index and word count
    for idx, filename in enumerate(filenames):
        with open(filename) as f:
            for sentence in f.readlines():
                words = sentence.strip().split()
                for word in words:
                    # word = process(word)  # Do more preprocessing stuff here if you need
                    if rare_word_flag and (word in single_words):
                        word_index[word] = 1
                        continue
                    if word in word_index:
                        continue
                    word_index[word] = word_count
                    word_count += 1
    return word_index, word_count


filenames = ["haha.txt"]
word_idx, word_count = create_word_index(filenames, False)
print(word_idx)
print(word_count)

# haha.txt file:
name=huhu, check=ok
name=haha, check=not good
0 голосов
/ 14 июля 2020

Если между словами есть запятая, вы можете сделать words = i.split(',') или что-то еще, что разделитель передан в качестве аргумента для split()

...