【问题标题】:Access words by index in python在python中按索引访问单词
【发布时间】:2020-07-13 23:31:14
【问题描述】:

我不知道这是否可能,但我正在尝试通过索引从拆分字符串中访问单词(不是单个字符)并将其存储在字典中。如果这不起作用,请就如何获得相同的结果提出任何其他建议。到目前为止,这是我的代码:

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 
       

【问题讨论】:

  • 如果您提供一些上下文(例如 CSV 的结构和最终数据结构的样例)会有所帮助。您是否希望通过表示包含特定键的 CSV 行列表的单词和值来保存字典?如果是这种情况,您可以枚举数据,并使用 setdefault 将单词添加为键(如果它尚不存在)并附加生成器中的当前索引。我们可以为您提供更多背景信息。 :)
  • 我更新了代码以显示 csv 文件的结构以及我希望它之后的样子

标签: python cs50


【解决方案1】:

如果单词之间有逗号,那么您可以使用words = i.split(',') 或任何分隔符作为参数传递给split()

【讨论】:

    【解决方案2】:
    sentence = 'This is an example'  # string: 'This is an example'
    words = sentence.split()         # list of strings: ['This', 'is', 'an', 'example']
    

    此时你可以通过调用它的索引来获取一个特定的单词,或者像for word in words:那样循环遍历它们。

    我不确定您代码的 SQL 部分,但看起来您在执行 for i in names: 时已经在循环这些单词。

    【讨论】:

    • 这是否意味着此语法正确:` ...names = row['name'].split() if len(names) == 2: name_column = {'first name' = name [0]}...
    【解决方案3】:

    你可以试试这段代码

    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
    

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 2017-07-29
      • 1970-01-01
      • 2016-12-19
      • 2011-12-10
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      相关资源
      最近更新 更多