语法是正确的,但运行速度非常慢。我怎么能改进这段代码?

时间:2018-03-23 11:20:16

标签: python nlp

var  service = [{id: '1', name: 'gana', age: '21', spare: 'rinch'}];
service.forEach(e => e.all = []);
console.log(service);

代码工作正常但速度非常慢。 这是一个简单的功能,不应该花这么长时间来回应。 我想知道是否有办法加快速度。

2 个答案:

答案 0 :(得分:1)

一些事情:

@Override
        public void onPageSelected(int position) {


            if (position >=previousPosition) {


                recyclerView.smoothScrollToPosition(position+1);
            } else {


                if(position>0)
                recyclerView.smoothScrollToPosition(position-1);
            }
            previousPosition = position;

            RecyclerView.ViewHolder 

       viewHolder=recyclerView.findViewHolderForAdapterPosition(position);

            if(viewHolder!=null)
                  viewHolder.itemView.setBackgroundColor(R.color.lightGrey);
            else
            {
                recyclerView.smoothScrollToPosition(position);

             recyclerView.findViewHolderForAdapterPosition(position).itemView.setBackgroundColor(R.color.lightGrey);    //  **this line giving me nullPointerException**

            }






        }

Timeit表示新版本的速度提高了约140倍:

import collections   # We'll use `collections.Counter`; it could be optimized
# Make a set of the stopwords, and don't recompute it for
# each invocation of `vocab`
stopword_set = set(nltk.corpus.stopwords.words('english'))

def vocab2(text):
    # Flip the order of stopword testing and isalpha;
    # we assume isalpha is faster, and since `and` is short-circuited,
    # if it returns False, the stopword testing is not done.
    text = [w for w in text if w.isalpha() and w not in stopword_set]
    return [w for w, n in collections.Counter(text).most_common(50)]

答案 1 :(得分:0)

你没有说你的代码的哪一部分很慢,但这是可能的。

nltk.corpus.stopwords.words('english')返回一个列表。在开始迭代文本之前,可以通过将其内容放在一个集合中来加快代码速度。

stopwords = set(nltk.corpus.stopwords.words('english'))
vocab = [w for w in text if w not in stopwords and w.isalpha()]

在集合中查找内容通常非常快。